Search code examples
reactjswebpackbabel-loader

Babel Loader and Webpack + React syntax error


I'm using React + Webpack and Babel Loader for my project.

When I'm trying to generate the bundle code, the following error is thrown (for every reducer I have when using {... state}):

@ ./src/reducers/index.js 29:21-47
 @ ./src/index.js

ERROR in ./src/reducers/logged_navbar.js
Module build failed: SyntaxError: C:/xampp/htdocs/scoala-de-iarna/src/reducers/logged_navbar.js: Unexpected token (8:12)

   6 |                  let data = _.mapKeys(action.payload.data, 'id');
   7 |                  state.navbarLogged = data;
>  8 |                  return { ...state };
     |                           ^
   9 |          default: return state;
  10 |  }
  11 | }

However, when testing the app on the developer build, this error is not shown.

webpack.config.js:

var webpack = require('webpack');
var path = require('path');

var BUILD_DIR = path.resolve(__dirname, 'src/bundle');
var APP_DIR = path.resolve(__dirname, 'src');

var config = {
  entry: APP_DIR + '/index.js',
  output: {
    path: BUILD_DIR,
    filename: 'bundle.js'
  },
  module: {
    loaders: [
      {
        test: /\.jsx?$/,
        include: APP_DIR,
        exclude: /node_modules/,
        loader: 'babel-loader',
      }
    ]
  }
};

module.exports = config;

.babelrc:

{
    "presets" : ["es2015", "react"]
}

Solution

  • Solution 1

    Install and add "stage2" to presets

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

    "presets" : ["es2015", "react", "stage-2"]

    Solution 2

    Install and add babel-plugin-transform-object-rest-spread to plugins

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

    { "plugins": ["transform-object-rest-spread"] }