【问题标题】:Webpack 4, babel 7, react, typescript: Unexpected token, expected ","Webpack 4,babel 7,反应,打字稿:意外的令牌,预期的“,”
【发布时间】:2020-06-11 09:05:23
【问题描述】:

错误:

ERROR in ./src/client/index.tsx
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: ***\src\client\index.tsx: Unexpected token, expected "," (5:16)

  3 | 
  4 | const a = {title: 'te'}
> 5 | const x = <span {...a}/>
    |                 ^
  6 | console.log(`>>>`, a)

webpack 配置:

import * as Webpack from 'webpack';
import {Compiler} from 'webpack';
import * as WebpackDevServer from 'webpack-dev-server';
import {paths} from './paths';
import {alias} from './alias';


const domain = ''
const createWebpackConfig = (): Webpack.Configuration => {
  const config: Webpack.Configuration = {
    mode: 'development',
    devtool: 'cheap-module-source-map',
    entry: [
      'react-hot-loader/patch',
      paths.appEntryFile,
    ],
    output: {
      // Add /* filename */ comments to generated require()s in the output.
      pathinfo: true,
      // This does not produce a real file. It's just the virtual path that is
      // served by WebpackDevServer in development. This is the JS bundle
      // containing code from all our entry points, and the Webpack runtime.
      filename: 'static/js/[name].bundle.js',
      // There are also additional JS chunk files if you use code splitting.
      chunkFilename: 'static/js/[name].chunk.js',
      // This is the URL that app is served from. We use "/" in development.
      publicPath: '/',
    },
    resolve: {
      alias,
      extensions: ['.tsx', '.ts', '.js', '.jsx'],
    },
    module: {
      rules: [
        {
          test: /\.(j|t)sx?$/,
          exclude: /node_modules/,
          use: {
            loader: 'babel-loader',
            options: {
              cacheDirectory: true,
              babelrc: false,
              presets: [
                ['@babel/preset-env', {
                  targets: '> 0.25%, not dead',
                  // Only add polyfills our code might need
                  useBuiltIns: 'usage',
                  debug: true,
                  // Looks like by default bable uses core-js 2 which breaks
                  corejs: 3,
                  modules: 'commonjs'
                }],
                '@babel/preset-react'
              ],
              plugins: [
                // To have `private` on class properties. `loose:true` to don't add bloat to the code.
                ['@babel/plugin-proposal-class-properties', {loose: true}],
                // Ability to do: `const enum`
                'babel-plugin-const-enum',
                // Ability to use typescript, has to be after 'babel-plugin-const-enum' otherwise will complain
                ['@babel/plugin-transform-typescript', {allowNamespaces: true}],
                'react-hot-loader/babel',
              ],
            },
          },
        },
        {
          test: /\.(png|jpe?g|gif)$/i,
          use: [
            {
              loader: 'file-loader',
            },
          ],
        },
      ]
    },
    plugins: [
    ],
    node: {
      fs: 'empty',
      net: 'empty',
      // Because of promise-request
      tls: 'empty'
    }
  }
  return config
}


const compiler = Webpack(createWebpackConfig());

const host = '127.0.0.1';
const devServerOptions: WebpackDevServer.Configuration = {
  open: false,
  host,
  hot: true,
  stats: {
    colors: true,
  },
}

const server = new WebpackDevServer(compiler, devServerOptions);

server.listen(3000, host, () => {
  console.log('Starting server on http://localhost:3000');
});

index.tsx:


import * as React from 'react';

const a = {title: 'te'}
const x = <span {...a}/>
console.log(`>>>`, a)

部分 package.json(加上更多废话):


    "@babel/core": "^7.8.4",
    "@babel/plugin-proposal-class-properties": "^7.8.3",
    "@babel/plugin-transform-typescript": "^7.8.3",
    "@babel/polyfill": "^7.8.3",
    "@babel/preset-env": "^7.8.4",
    "@babel/preset-react": "^7.8.3",
    "babel-cli": "^6.26.0",
    "babel-jest": "^25.1.0",
    "babel-loader": "^8.0.6",
    "babel-plugin-const-enum": "^0.0.5",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react-app": "^9.1.1",

我不知道为什么它不起作用。我有 react 插件,所以它应该能理解 react,"babel-loader": "^8.0.6",

【问题讨论】:

    标签: reactjs typescript webpack


    【解决方案1】:

    通过添加 babel 预设修复:['@babel/preset-typescript', {allowNamespaces: true}],

    我不知道为什么 react 会中断...

    【讨论】:

      【解决方案2】:

      我遇到了同样的问题。为了解决这个问题,我有

      • 通过运行安装@babel/preset-typescript

         yarn add @babel/preset-typescript
        
      • 添加

         ['@babel/preset-typescript', {allowNamespaces: true}]
        

      在 webpack.config.js 中像这样

      rules: [
              {
                  test: /\.[tj]sx?$/,
                  include: /(src)/,
                  use: [{
                      loader: 'babel-loader',
                      options: {
                          presets: [
                              [
                                  '@babel/preset-env',
                                  {
                                      "useBuiltIns": "usage",
                                      "corejs": 3
                                  }
                              ],
                              ['@babel/preset-typescript', { allowNamespaces: true }]
                          ],
                          plugins: [
                              '@babel/plugin-syntax-dynamic-import'
                          ]
                      }
                  }]
              },
              {
                  test: /\.tsx?$/,
                  include: path.resolve(__dirname, "src"),
                  use: [{
                      loader: 'ts-loader',
                      options: {
                          transpileOnly: true
                      }
                  }]
              },
              {
                  test: /\.css$/,
                  use: ['style-loader', 'css-loader']
              },
              {
                  test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/,
                  use: [{
                      loader: 'url-loader',
                      options: {
                          limit: 10000,
                      }
                  }]
              }
          ]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-09-16
        • 2019-03-04
        • 1970-01-01
        • 2016-07-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多