webpack tsx模块解析失败:意外的令牌

时间:2020-07-30 13:32:22

标签: node.js reactjs typescript webpack

我正在尝试在TypeScript中同时编写前端(反应)和后端(表达)。此刻,即使我有webpack.config.js,我在根文件夹中的ts-loader也会遇到错误。

这是webpack.config.js

const webpack = require('webpack');
const path = require('path');

const config = {
    cache: true,
    mode: 'development',
    entry: {
        'user': ['./src/client/User/index.tsx', 'webpack-hot-middleware/client']
    },
    output: {
        filename: '[name].bundle.js',
        path: path.resolve(__dirname, 'dist'),
        publicPath: '/static'
    },
    devServer: {
        contentBase: './dist',
        hot: true
    },
    plugins: [new webpack.HotModuleReplacementPlugin()],
    resolve: {
        extensions: ['.tsx', '.ts', '.js']
    },
    module: {
        rules: [
            {
                test: /\.tsx?$/,
                loader: 'ts-loader',
                exclude: /node_modules/,
                include: path.join(__dirname, 'client')
            }
        ]
    },
    node: { fs: 'empty' }
};

module.exports = config;

这是我的tsconfig.json

{
    "compilerOptions": {
        "target": "es6",
        "module": "commonjs",
        "moduleResolution": "node",
        "jsx": "react",
        "esModuleInterop": true,
        "outDir": "dist",
        "sourceMap": true,
        "baseUrl": "."
    },
    "include": ["src/**/*.ts"],
    "exclude": ["node_modules"]
}

我收到这样的错误:

ERROR in ./src/client/User/index.tsx 10:1
Module parse failed: Unexpected token (10:1)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
|
| const rootComponent = (
>       <Provider store={store}>
|               <BrowserRouter>
|                       <div id="page-container" className="sidebar-o sidebar-dark enable-page-overlay side-scroll page-header-fixed side-trans-enabled">
 @ multi ./src/client/User/index.tsx webpack-hot-middleware/client user[0]

2 个答案:

答案 0 :(得分:1)

include中的tsconfig部分更改为以下内容

{
    ...
    "include": [
        "src/**/*.ts", 
        "src/**/*.tsx"
    ],
    ...
}

答案 1 :(得分:1)

感谢FunkeyFlo的答案,我自己找到了答案。我都必须同时更改:

  • tsconfig.jsoninclude也是src/**/*.tsx
  • webpack.config.js:从entry./dist/src/client/User/index