问题描述
我是用webpack构建了一个react项目,在使用redux的时候总是报 ... 语法错误
ERROR in ./src/reducer.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: Unexpected token (10:15)
8 | switch (action.type) {
9 | case 'CHANGE_COLOR':
> 10 | return { ...state, themeColor: action.themeColor };
| ^
11 | default:
12 | return state;
13 | }
@ ./src/index.js 19:15-35
问题出现的环境背景及自己尝试过哪些方法
webpack.config.js
const path = require('path');
module.exports = {
entry: path.resolve(__dirname, './src/index.js'), //指定入口文件,程序从这里开始编译,__dirname当前所在目录, ../表示上一级目录, ./同级目录
output: {
path: path.resolve(__dirname, './dist'), // 输出的路径
filename: 'bundle.js' // 打包后文件
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
loader: 'babel-loader',
exclude: /node_modules/
}
]
}
}
package.json
{
"name": "first-react",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "webpack --config webpack.config.js",
"dev": "node bin/dev-server -open"
},
"author": "",
"license": "ISC",
"dependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^7.1.5",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"prop-types": "^15.6.2",
"react": "^16.5.2",
"react-dom": "^16.5.2",
"react-redux": "^5.0.7",
"redux": "^4.0.0",
"webpack-dev-server": "^3.1.9"
},
"devDependencies": {
"webpack": "^4.20.2",
"webpack-cli": "^3.1.1"
}
}
相关代码
index.js
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import themeReducer from './reducer';
const store = createStore(themeReducer);
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('app'));
App.js
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
class App extends Component {
static propTypes = {
themeColor: PropTypes.string
};
render() {
return (
<div style={{ color: this.props.themeColor }}>Hello React! xixi</div>
);
}
}
const mapStateToProps = (state) => {
return {
themeColor: state.themeColor
};
}
Header = connect(mapStateToProps)(Header);
export default App;
reducer.js
//reducer.js
const themeReducer = (state, action) => {
if (!state) {
return {
themeColor: 'red'
};
}
switch (action.type) {
case 'CHANGE_COLOR':
return { ...state, themeColor: action.themeColor };
default:
return state;
}
}
export default themeReducer;
你期待的结果是什么?实际看到的错误信息又是什么?
请问这种错误我该怎么解决,相同的代码在create-react-app构建出来的项目中可以完美运行
错误信息如下
ERROR in ./src/reducer.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: Unexpected token (10:15)
8 | switch (action.type) {
9 | case 'CHANGE_COLOR':
> 10 | return { ...state, themeColor: action.themeColor };
| ^
11 | default:
12 | return state;
13 | }
@ ./src/index.js 19:15-35
babel 引入包如下
配置文件如下
.babelrc
webpack.config.js如下
package.json