You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Webpack编译Redux Todos示例报错,求扩展运算符写法失败原因

Why Object Spread Syntax Failed in Your Webpack/Redux Build

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:

  1. Install the required plugin:
    npm install --save-dev @babel/plugin-proposal-object-rest-spread
    
  2. Add it to your Babel config file (.babelrc or babel.config.js):
    {
      "plugins": ["@babel/plugin-proposal-object-rest-spread"]
    }
    
    Alternatively, if you're using @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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:34:42