2016-04-08 140 views
0

我正在嘗試使用反應設置開發環境中的應用程序寫在打字稿。 我擁有現有的打印腳本代碼,可編譯爲ES5和AMD模塊。NPM + React + TypeScript與AMD模塊

我想避免瀏覽器中的任何js轉換。請注意,我不需要使用babel來傳輸jsx,因爲typescript將標籤編譯到tsx文件中的React.createElement中。

我已經做了平常:

npm install react -save 
npm install react-dom -save 

npm install typescript -save-dev 
npm install typings -save-dev 

typings install react --ambient --save 
typings install react-dom --ambient --save 

現在,我有兩個問題:

  1. 如何正確導入/需要我的TSX文件的反應和反應-DOM編譯爲ES5/AMD?

    目前我只是在做這樣的:

    /// <reference path="../../typings/browser/ambient/react-dom/index.d.ts" /> 
    /// <reference path="../../typings/browser/ambient/react/index.d.ts" /> 
    
    export class MyComponent extends __React.Component<any, {}> {  
        public render() { 
        return (
         <h1>MyCompoentnt</h1> 
        ); 
        } 
    } 
    

    但是編譯失敗,錯誤TS2304:找不到名稱「作出反應」。

  2. 如何在我的應用程序中包含react.js和react-dom.js?我需要一些轉譯或瀏覽。或者我應該只是和他們index.html?

    <script src="scripts/react.js"></script> 
    <script src="scripts/react-dom.js"></script> 
    <script src="scripts/require.min.js" data-main="scripts/app"></script> 
    

這裏是我的package.json:

{ 
    "name": "myhtmlapp", 
    "version": "1.0.0", 
    "description": "react test app", 
    "main": "index.js", 
    "dependencies": { 
    "jquery": "^2.2.3", 
    "react": "^15.0.0", 
    "react-dom": "^15.0.0" 
    }, 
    "devDependencies": { 
    "browser-sync": "^2.11.2", 
    "typescript": "^1.8.9", 
    "typings": "^0.7.12" 
    }, 
    "scripts": { 
    "watch:typescript": "tsc --p ./appscripts -w", 
    "watch:css": "browser-sync start --server --files .wwwroot/css/*.css", 
    "compile": "tsc --p ./appscripts", 
    "test": "echo \"Error: no test specified\" " 
    }, 
    "keywords": [], 
    "author": "", 
    "license": "ISC" 
} 

這裏是整個應用程序:https://onedrive.live.com/redir?resid=51A46BBA4E9EF07E!263323&authkey=!AKQ6FqjE2W2YVBo&ithint=file%2czip

回答

0

我敢肯定,有多種方法可以做到這一點。下面我張貼把事情做我的方式你提到一起玩:

  1. 要導入反應我使用標準import,像這樣:

    import * as React from 'react'; 
    import * as ReactDOM from 'react-dom'; 
    
    export class MyComponent extends React.Component<any, any> 
    { 
        //... 
    } 
    
  2. 要「inculde」反應到應用程序中我使用systemjs作爲模塊加載器(由於某些原因導致的問題,我不能使用browserify,但很確定它可以用來做同樣的事情)。您需要通過npm安裝systemjs。然後指示它知道在哪裏尋找反應。要做到這一點把下面的腳本在您的index.html:

    <script src="systemjs/dist/system.src.js"></script> 
    
    <script> 
        System.config({ 
         baseURL: './lib', 
         paths: { 
          "react*": 'react/dist/react-with-addons' 
         }    
        }); 
    
        System.defaultJSExtensions = true; 
    </script> 
    

    react/dist/react-with-addons是路徑(無」的.js'擴展)反應與 - addons.js的DIST。和systemjs/dist/system.src.js - systemjs dist的路徑。

希望這會有所幫助。

+0

我已經在使用requirejs來加載amd模塊。使用systemjs也不奇怪嗎? – Liero

+0

如果需要,我相信你可以使用requirejs。我同意將兩個裝載者合併在一起不是個好主意。有很多關於如何在requirejs中使用typescript的教程。這個想法是一樣的。 – Amid

相關問題