关于reactjs:Babel Loader和Webpack React语法错误

Babel Loader and Webpack + React syntax error

我正在为我的项目使用React Webpack和Babel Loader。

当我尝试生成捆绑代码时,会引发以下错误(对于使用{... state}时所拥有的每个reducer):

1
2
3
4
5
6
7
8
9
10
11
12
13
@ ./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 | }

但是,在开发人员版本上测试应用程序时,不会显示此错误。

webpack.config.js:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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:

1
2
3
{
   "presets" : ["es2015","react"]
}


解决方案1 ??

安装" stage2"并将其添加到预设

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

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

解决方案2

安装babel-plugin-transform-object-rest-spread并将其添加到插件

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

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


对象传播算子目前仍是第3阶段的提议,尚未最终因此,它不包含在babel核心中。

要使用babel进行编译,请在babel配置中包括预设的第3阶段:

1
2
3
{
   "presets" : ["es2015","stage-3","react"]
}