【问题标题】:ReactJS: webpack: Failed to compile with spread syntaxReactJS:webpack:无法使用扩展语法编译
【发布时间】:2018-07-06 13:40:50
【问题描述】:

我想告诉你我的问题。

我的环境:

Node: 8.9.1
npm: 5.6.0
yarn: 1.3.2

package.json

  "devDependencies": {
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.2",
    "babel-plugin-transform-object-rest-spread": "^6.26.0",
    "babel-preset-env": "^1.6.1",
    "babel-preset-react": "^6.24.1",
    "copy-webpack-plugin": "^4.1.1",
...
    "webpack": "^3.7.1",
    "webpack-dev-server": "^2.9.2"
  },

webpack.config.js

...
    module: {
      rules: [
        {
          test: /\.(js|jsx)$/,
          exclude: /node_modules/,
          use: {
            loader: 'babel-loader',
            options: {
              cacheDirectory: true,
              presets: ['react', 'env']
            }
          }
        },
...

在 {...} 上总是编译失败

./src/flux/components/BaseComponent.js 中的错误模块构建失败: SyntaxError:D:/APPs/src/flux/components/BaseComponent.js:意外 令牌 (36:29)

 34 |     let {search} = this.state;
  35 |     search.includeActive = !search.includeActive;
> 36 |     this.setState({category : {...this.state.category, name : name}});

     |

但是,它在没有 webpack 的情况下运行良好。 请帮我解决这个问题! 非常感谢你们所有人! :)

【问题讨论】:

  • 安装 babel-preset-state-0 并将其添加到预设预设中:['react', 'env', 'stage-0] 以使用扩展语法

标签: reactjs webpack ecmascript-6 babeljs


【解决方案1】:

为了使用扩展语法,你需要配置你的 babel loader,你有几个选项

第一:使用插件"transform-object-rest-spread"

使用安装它

npm install --save-dev babel-plugin-transform-object-rest-spread

并使用它

   options: {
       cacheDirectory: true,
       presets: ['react', 'env']
       plugins: ['transform-object-rest-spread']
   }

第二:使用stage-0预设,使用安装

npm install --save-dev babel-preset-stage-0

并像使用它

options: {
   cacheDirectory: true,
   presets: ['react', 'env', 'stage-0']
}

检查this babel-documentation

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-21
    • 2019-01-25
    • 2019-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多