ReactJS:webpack:无法使用扩展语法进行编译

IT技术 reactjs webpack ecmascript-6 babeljs
2021-04-20 22:23:36

我想告诉你我的问题。

我的环境:

Node: 8.9.1
npm: 5.6.0
yarn: 1.3.2

包.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 module构建失败:语法错误: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 的情况下运行良好。请帮我解决这个问题!非常感谢你们所有人!:)

1个回答

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

第一:使用插件"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']
}

检查这个 babel-documentation