使用Webpack和React的意外令牌

时间:2017-03-02 22:31:47

标签: reactjs typescript webpack

我是TypeScript的新手,对React来说相对较新,只是想跟随React & Webpack tutorial。通过一些搜索,我设法解决了大部分问题,因为它有点过时,除了一个。当我尝试运行Webpack来转换Typescript时,我得到:

ERROR in ./src/index.tsx
Module parse failed: /home/X/Projects/react-typescript-tutorial/src/index.tsx Unexpected token (7:4)
You may need an appropriate loader to handle this file type.
| 
| ReactDOM.render(
|     <Hello compiler="TypeScript" framework="React" />,
|     document.getElementById("example")
| );

我尝试了this previous question中提到的解决方案,但它对我的情况没有影响。我不确定这是awesome-typescript-loader这个问题还是Webpack。

我的webpack.config.js文件:

module.exports = {
    entry: "./src/index.tsx",
    output: {
        filename: "bundle.js",
        path: __dirname + "/dist"
    },

    devtool: "source-map",

    resolve: {
        extensions: ["*", ".webpack.js", ".web.js", ".ts", ".tsx", ".js"]
    },

    module: {
        loaders: [
            { test: /\.tsx?$/, loader: "awesome-typescript-loader" }
        ],

        rules: [
            { test: /\.js$/, enforce: "pre", loader: "source-map-loader" }
        ]
    },

    externals: {
        "react": "React",
        "react-dom": "ReactDOM"
    },
};

我的tsconfig.json:

{
    "compilerOptions": {
        "outDir": "./dist/",
        "sourceMap": true,
        "noImplicitAny": true,
        "module": "commonjs",
        "target": "es5",
        "jsx": "react"
    },
    "include": [
        "./src/**/*"
    ]
}

并且(根据评论中的要求)我的index.tsx文件:

import * as React from "react";
import * as ReactDOM from "react-dom";

import { Hello } from "./components/Hello";

ReactDOM.render(
    <Hello compiler="TypeScript" framework="React" />,
    document.getElementById("example")
);

感谢任何有用的帮助!

1 个答案:

答案 0 :(得分:9)

您定义了module.rulesmodule.loaders。当webpack看到module.rules时,它会完全忽略module.loaders,这仅出于兼容性原因而存在。所以你的awesome-typescript-loader根本没用过。要解决此问题,只需将所有规则置于modules.rules

module: {
   rules: [
      { test: /\.tsx?$/, loader: "awesome-typescript-loader" },
      { test: /\.js$/, enforce: "pre", loader: "source-map-loader" }
   ]
},