简体   繁体   中英

SyntaxError using spread operator in webpack.config.js

In my webpack.config.js i am importing several JS objects for the configuration from other files. These object are composed using spread operator. Ex. in build.js

const otherObj = { a:[], b: [] }
const conf = {
  prop1: [],
  ...otherObj
}

Then i want to use these objects in the webpack.config.js in this way:

const { prop1, a, b } = require('./build.js');
module.exports = {
    entry: { prop1, a, b },
    rules: [
      {
        test: jsRegex,
        exclude: /node_modules/,
        use: ["babel-loader"]
      },
    ]
}

When i launch the build script i get a SyntaxError:

    ...otherObj,
^^^
SyntaxError: Unexpected token ...

NOTE: Here follows the .babelrc

    {
    "presets": [
        "@babel/preset-env"
    ],
    "plugins": [
        "@babel/syntax-object-rest-spread"
    ] 
}

That depends on the version of node that you are using. For example, using node v6.15.1 (Boron) will return the same error you have, but when running on v8.14.0 (Carbon) it compiles just fine.

Use node

Check that the node version you are using supports the features you need.

The feature you are using object spread properties was added on v8.6.0 (running node without flags).

Use babel

You can transpile your webpack config , this way you can use your current node version and use all the ES6 features you may like.

You should add .babelrc file like this below.

Then do install: npm i babel-plugin-transform-object-rest-spread

{
    "presets": ["env", "react"],
    "plugins": ["transform-object-rest-spread"]

}

This is worked for Me, try it!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM