【问题标题】:Unexpected token with Webpack and ReactWebpack 和 React 的意外令牌
【发布时间】:2017-07-22 21:04:09
【问题描述】:

我是 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/**/*"
    ]
}

并且(根据 cmets 的要求)我的 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")
);

如果有任何帮助,我们将不胜感激!

【问题讨论】:

  • 还想查看 index.tsx 文件
  • 嗨@ArshabhAgarwal,我也添加了 index.tsx 内容。

标签: reactjs typescript webpack


【解决方案1】:

您同时定义了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" }
   ]
},

【讨论】:

    猜你喜欢
    • 2016-07-23
    • 2020-01-29
    • 2016-07-10
    • 1970-01-01
    • 1970-01-01
    • 2016-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多