【问题标题】:webpack 4 react unexpected token ...(spread operator)webpack 4对意外令牌做出反应......(传播运算符)
【发布时间】:2018-10-23 22:51:06
【问题描述】:

最近我为我的react 应用程序实现了Webpack 4 设置。

我的webpack.config.js 看起来像这样

const HtmlWebPackPlugin = require('html-webpack-plugin');

const htmlWebpackPlugin = new HtmlWebPackPlugin({
  template: './src/index.js',
  filename: './index.html',
});

module.exports = {
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
        },
      },
      {
        test: /\.css$/,
        use: [
          {
            loader: 'style-loader',
          },
          {
            loader: 'css-loader',
            options: {
              modules: true,
              importLoaders: 1,
              localIdentName: '[name]_[local]_[hash:base64]',
              sourceMap: true,
              minimize: true,
            },
          },
        ],
      },
    ],
  },
  plugins: [htmlWebpackPlugin],
};

这是我的package.json 脚本

"scripts": {
    "dev": "webpack-dev-server --mode development --open",
    "prod": "webpack --mode production"
}

这里的问题是,当我使用...(扩展运算符)时,它会抛出一个error,我相信这与babel 有关,它没有正确转译。任何建议,将不胜感激。谢谢。

它会抛出一个error 类似下面的东西。

 ERROR in ./src/index.js
    Module build failed: SyntaxError: D:/cp/src/index.js: Unexpected token (31:6)

      29 |   return {
      30 |     headers: {
    > 31 |       ...headers,
         |       ^
      32 |       authorization: token ? `Bearer ${token}` : null,
      33 |     },
      34 |   };

【问题讨论】:

  • ... 不是(也不能是)操作员。
  • @kiarashws:错误报告在.js 文件中,有什么帮助?
  • 你的 .babelrc 里有什么?
  • @wgcrouch { "presets": ["env", "react"] }

标签: javascript reactjs webpack babeljs


【解决方案1】:

只需安装babel-plugin-transform-object-rest-spread 模块。 https://www.npmjs.com/package/babel-plugin-transform-object-rest-spread

然后将其添加到.babelrc:

"plugins": [
    "babel-plugin-transform-object-rest-spread",
  ],

【讨论】:

  • 如果不使用 .babelrc 然后将以下内容添加到 webpack 配置中的模块规则选项下,插件:['transform-object-rest-spread']
【解决方案2】:
   "babel-plugin-transform-object-rest-spread"

甚至没有 github 页面。如果你使用它,你会在控制台上看到太多的输出,并且没有选项可以让它静音或使用“详细”。我建议你使用
@babel/plugin-transform-spread。然后将此添加到.babelrc

{
  "presets": ["@babel/preset-env", "@babel/preset-react"],
  "plugins": [
    "@babel/plugin-transform-spread"
  ]
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-18
    • 1970-01-01
    • 1970-01-01
    • 2020-06-11
    • 2019-01-17
    相关资源
    最近更新 更多