首页 文章

NPM React TypeScript与AMD模块

提问于
浏览
0

我正在尝试使用react设置用于使用reactcript编写的应用程序的开发环境 . 我真的有现成的打字稿代码编译成ES5和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

现在,我有两个问题:

  • how to correctly import/require the react and react-dom in my tsx files 编译成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:找不到名称'React' .

  • how to include react.js and react-dom.js in my app? 我想要一些转换或浏览器化 . 或者我应该和他们一起去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

1 回答

  • 0

    我很确定有几种方法可以做到这一点 . 下面我将发布你提到的东西的方式发布在一起:

    • 要导入反应我使用标准 import ,如下所示:
    import * as React from 'react';
    import * as ReactDOM from 'react-dom';
    
    export class MyComponent extends React.Component<any, any>
    {
        //...
    }
    
    • 为了'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 是react-with-addons.js的路径(没有'.js'扩展名) . 和 systemjs/dist/system.src.js - systemjs dist的路径 .

    希望这可以帮助 .

相关问题