[英]NPM + React + TypeScript with AMD modules
我正在尝试使用react为用打字稿编写的应用程序设置开发环境。 我总是有现有的打字稿代码,可以编译为ES5和AMD模块。
我想避免在浏览器中进行任何js转换。 请注意,我不需要使用babel来转换jsx,因为打字稿会将标签编译到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
现在,我有两个问题:
如何在导入到ES5 / AMD的tsx文件中正确导入/要求react和react-dom ?
目前,我只是在这样做:
/// <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:找不到名称“反应”。
如何在我的应用程序中包含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
我很确定有几种方法可以做到这一点。 下面我将发布我提到的东西一起玩的方式:
要导入react我使用标准import
,像这样:
import * as React from 'react'; import * as ReactDOM from 'react-dom'; export class MyComponent extends React.Component<any, any> { //... }
为了“灌输”对应用程序的反应,我将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
是react-with-addons.js的dist路径(不带'.js'扩展名)。 和systemjs/dist/system.src.js
-systemjs dist的路径。
希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.