使用Webpack编译Redux Todos示例报错,求扩展运算符写法失败原因
Hey Anthony! Let's break down why your first code snippet threw that syntax error, while the second one compiled smoothly.
The Core Issue: ES Feature Support Gap
Your initial approach used the object spread operator ({...todo, completed: !todo.completed}):
case 'TOGGLE_TODO': return state.map(todo => ( todo.id === action.id ? {...todo, completed: !todo.completed} : todo ))
This syntax is part of the ES2018 specification, which isn't included in the default transpilation rules of older or minimally configured Babel setups. Webpack relies on Babel to convert modern ES features into code that browsers (or your target environment) can understand—if Babel doesn't recognize the object spread syntax, it'll throw that Unexpected token error immediately.
On the flip side, your fix used Object.assign():
case 'TOGGLE_TODO': return state.map(todo => ( todo.id === action.id ? Object.assign({}, todo, {completed: !todo.completed}) : todo ))
Object.assign() is an ES2015 (ES6) feature, which is supported by almost all standard Babel presets (like @babel/preset-env with default settings, or the legacy babel-preset-es2015). Since Babel knows how to transpile this method into backward-compatible code, Webpack had no trouble processing it.
How to Enable Object Spread Syntax for Future Use
If you prefer the cleaner object spread syntax, you just need to update your Babel configuration to support it:
- Install the required plugin:
npm install --save-dev @babel/plugin-proposal-object-rest-spread - Add it to your Babel config file (
.babelrcorbabel.config.js):
Alternatively, if you're using{ "plugins": ["@babel/plugin-proposal-object-rest-spread"] }@babel/preset-env, you can define your target environments explicitly—Babel will automatically include this plugin if your target environments don't natively support object spread.
内容的提问来源于stack exchange,提问作者Anthony.SYX

