带有React类型的TypeScript将无法编译

时间:2017-08-15 14:09:49

标签: reactjs typescript webpack typescript-typings

我尝试按照TypeScript page进行设置,但是我遇到了一些错误。我的档案在这里:

tsconfig:

{
  "compilerOptions": {
    "outDir": "../scripts/",
    "noImplicitAny": false,
    "noEmitOnError": true,
    "removeComments": true,
    "sourceMap": true,
    "target": "es5",
    "jsx": "react",
    "lib": [
      "es6",
      "es5",
      "dom"
    ]
  },
  "exclude": [
    "node_modules",
    "wwwroot",
    "scripts"
  ]
}

的package.json:

{
  "version": "1.0.0",
  "name": "asp.net",
  "private": true,
  "devDependencies": {
    "@types/react": "latest",
    "@types/react-dom": "latest",
    "typescript": "2.4.2",
    "awesome-typescript-loader": "3.2.3",
    "source-map-loader": "0.2.1",
    "gulp": "3.9.1",
    "del": "2.2.2",
    "gulp-concat": "2.6.1",
    "gulp-sourcemaps": "2.6.0",
    "gulp-uglify": "2.1.2",
    "@types/jquery": "2.0.41",
    "pump": "1.0.2",
    "@types/bootstrap": "3.3.33",
    "gulp-typescript": "3.1.7",
    "@types/knockout": "3.4.41",
    "ts-loader": "2.3.2",
    "webpack": "3.5.4",
    "webpack-stream": "4.0.0"
  },
  "dependencies": {
    "react": "latest",
    "react-dom": "latest"
  }
}

webpack.config.js:

module.exports = {
    entry: "./typescripts/index.tsx",
    output: {
        filename: "bundle.js",
        path: __dirname + "/scripts"
    },
    devtool: "source-map",    
    resolve: {
        extensions: [".ts", ".tsx", ".js", ".json"]
    },    
    module: {
        rules: [
            { test: /\.tsx?$/, loader: "awesome-typescript-loader" },
            { enforce: "pre", test: /\.js$/, loader: "source-map-loader" }
        ]
    },
    externals: {
        "react": "React",
        "react-dom": "ReactDOM"
    }

我的tsx文件是从上面链接的页面复制/粘贴的。

我得到的第一个错误是awesome-typescript-loader

ERROR in ./typescripts/index.tsx
Module parse failed: c:\Documents\Visual Studio 2017\Projects\DevSln\WebApplication4\node_modules\awesome-typescript-loader\dist\entry.js!C:\Documents\Visual Studio 2017\Projects\DevSln\WebApplication4\typescripts\index.tsx Unexpected token (6:16)
You may need an appropriate loader to handle this file type.
| var ReactDOM = require("react-dom");
| var Hello = require("./hello");
| ReactDOM.render(<Hello.Hello compiler="typescript" framework="React"/>, document.getElementById("example"));
| 

如果我将加载程序切换到ts-loader,这个错误就会消失,但我仍然想知道我是否做错了。

第二个错误是@types\react类型定义。它给我带来了各种类型的错误。但是列表中的第一个是:

Severity    Code    Description Project File    Line    Suppression State
Error       Build:Module '"C:/Documents/Visual Studio 2017/Projects/DevSln/WebApplication4/node_modules/@types/react/index"' has no exported member 'DOMAttributes'.    WebApplication4 C:\Documents\Visual Studio 2017\Projects\DevSln\WebApplication4\node_modules\@types\react-dom\index.d.ts    15  

这使我无法构建我的解决方案。我正在使用VS2017。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

不知道它是否是正确的答案,但它有效并且我没有丢失打字。为了解决这个问题,我删除了"@types/react": "latest" 和packages.json

中的"@types/react-dom": "latest"