Search code examples
reactjswebpackbabeljsecmascript-next

Getting object spread to work with webpack.config and babelrc files


I am trying to get the object spread operator to work with my react project. It comes up with a syntax error:

spread operator error

I have tried using babel-plugin-transform-object-rest-spread as described by the babel docs.

After a bit of research I also tried the config described in GitHub issues for babel: babelrc config for spread operator

Please see my .babelrc file below:

{
    "presets": ["es2015"],
    "plugins": ["transform-object-rest-spread"],
    "sourceMaps": true,
    "retainLines": true
}

And my webpack.config file below:

const path = require('path');

module.exports = {
  entry: './src/index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'public', 'js'),
    publicPath: '/'
  },
  devtool: 'source-map',
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        include: path.resolve(__dirname, 'src'),
        loader: 'babel-loader',
        options: {
          presets: ['react', 'es2015']
        }
      },
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader']
      },
      {
        test:/\.scss$/,
        use: [{
                loader: 'style-loader'
            }, {
                loader: 'css-loader'
                }, {
                loader: 'sass-loader', options: {
                    sourceMap: true
                }
            }]
      },
      {
        test: /.(png|jpg|jpeg|gif|svg|woff|woff2|eot|ttf)(\?v=\d+\.\d+\.\d+)?$/,
        loader: 'url-loader'
      }
    ]
  },
  devServer: {
   historyApiFallback: true,
   contentBase: path.join(__dirname, 'public'),
   publicPath: '/js/',
   port: 3000
 }
};

And my code where I'm using the spread operator is:

import * as types from '../types/types'; 

const initialState ={
    mesage:''
}

export default function doodlesReducer (state = initialState, action) {
    switch(action.type) {
        case 'SET_MESSAGE' :
        return {…state, message: action.payload.message}
        default :
        return state
        }
}

Can anyone help me try and figure out the right configuration to use the object spread operator?


Solution

  • You're listing your presets in both .babelrc and webpack.config, try moving it all out to only one of them, i.e. only .babelrc:

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

    Edit: Also instead of using es2015 preset which has now been deprecated install an env preset npm install --save-dev babel-preset-env and in .babelrc replace es2015 with env.

    Edit 2: The that you're using uses some non-supported character encoding, you must have copy pasted it from somewhere which messed up the encoding, replace it with ....