Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

webpack 4 react unexpected token ...(spread operator)

Recently i have implemented Webpack 4 setup for my react app.

My webpack.config.js looks like this

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],
};

Here is my package.json scripts

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

Here the problem is when i use ...(spread operator) it's throwing an error i believe this is something related to babel which is not properly transpiling. Any suggestions would be appreciated. Thanks.

It throws an error something like the one below.

 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 |   };
like image 560
Murali N Avatar asked Dec 04 '22 20:12

Murali N


2 Answers

Just install babel-plugin-transform-object-rest-spread module. https://www.npmjs.com/package/babel-plugin-transform-object-rest-spread

Then add it to .babelrc:

"plugins": [
    "babel-plugin-transform-object-rest-spread",
  ],
like image 128
Serge Nikolaev Avatar answered Dec 06 '22 11:12

Serge Nikolaev


   "babel-plugin-transform-object-rest-spread"

does not even have a github page. if you use this, you will see too much output on the console and there is no option to silent it or use "verbose". I suggest you to use
@babel/plugin-transform-spread. then add this to the .babelrc

{
  "presets": ["@babel/preset-env", "@babel/preset-react"],
  "plugins": [
    "@babel/plugin-transform-spread"
  ]
}
like image 39
Yilmaz Avatar answered Dec 06 '22 10:12

Yilmaz