Babel-loader: unexpected token (rest spread operator)

Created on 29 Nov 2015  路  55Comments  路  Source: babel/babel-loader

Webpack Config

module.exports = {
  entry: './src/public/client.jsx',
  output: {
    path: path.resolve(__dirname, 'public'),
    filename: 'bundle.js'
  },
  module: {
    loaders: [
      {
        test: /\.jsx?$/,
        exclude: /(node_modules|.cache)/,
        loader: 'babel',
        query: {
          presets: ['react', 'es2015'],
          plugins: ['syntax-decorators']
        }
      }
    ]
  }
}

screen shot 2015-11-29 at 1 10 32 pm

es2015 includes object rest support, then why am I facing this issue?

UPDATE:

It starts working when i add transform-object-rest-spread to plugins.

Most helpful comment

Here is a .babelrc that works for doing things like

const store = createStore(
  combineReducers({
    ...reducers,
    routing: routerReducer
  })
)

.babelrc

{
  "presets": ["react", "es2015"],
  "plugins": ["transform-es2015-destructuring", "transform-object-rest-spread"]
}

You can install the two plugins with:

npm install --save-dev babel-plugin-transform-es2015-destructuring

&

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

All 55 comments

What you're trying to do is a stage2 feature. You can either add the plugin as you have done or add the entire stage2 preset. For more information, see https://github.com/sebmarkbage/ecmascript-rest-spread.

But its not documented anywhere, that this is how I should be using it.

I agree that the documentation is lacking for the Babel plugins, but it's important to realize what is actually supported by ES2015--it seems that is at the root of you confusion. I recommend looking at http://kangax.github.io/compat-table/es6/ and http://es6-features.org/ for what is actually supported. What you're trying to do is an ES7 feature. In the first link, you can change the ES version at the top, and you may also click on the Babel column to see which features are specifically supported by Babel.

I should also add there's no reason you can't use ES7 features. Just be wary of them as their implementation may change.

so what is the minimal config I need for this?

I tried this:

     `presets: ['react', 'es2015','stage-2']?`

but still get errors

@QuantumInformation Please drop by one of our support channels: https://github.com/babel/babel#looking-for-support That config should be fine, so it's likely an issue elsewhere.

@QuantumInformation - Did you ever get to the bottom of the issue? I'm facing the same problem. I'm trying to work out what the minimum config is to get {...obj} working.

transform-object-rest-spread plugin or stage-2 preset. you can try it in the repl too

In my case I just installed stage-0 and added it on my .babelrc file, that solved for me.

+1 for updating babel docs.
Can someone tell me where I'm misunderstanding here?
The Babel homepage says that this feature is called Object Rest/Spread and that it's included by using the transform-es2015-destructuring plugin. The es2015 preset page says that this plugin is included by default in its preset. [es2015]

So can someone explain why that means I need to do more then simply:

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

@iDVB {...obj} is object rest/spread and it's not in es2015. It's an experimental feature. I mentioned above you need transform-object-rest-spread plugin or stage-2 preset. It's not included in es2015 because it's not in the spec yet and not part of react.

transform-es2015-destructuring involves a(...a), [...d] - over lists/arrays. ... with an object is different

gotcha. Thanks!

@hzoo unfortunately, the _implementation_ is actually in the transform-es2015-destructuring. If you use only transform-object-rest-spread, spreads will be transformed, but rests will be left untouched and cause syntax errors.

It looks like things have changed once again as preset-stage-2 now have transform-decorators (crossed out) because of disabled pending proposal update

After many hours searching for info and lots of trial and error, I have tried every combination of plugins and presets possible, yet none of them have worked. Can someone please confirm a set up that works? I am running Node V6.2.2

The issue is https://github.com/babel/babel/issues/4074: my wip pr is https://github.com/babel/babel/pull/4755

You'll need babel-plugin-transform-es2015-parameters and babel-plugin-transform-es2015-destructuring since the plugin relies on them for desctructuring until we are able to make it work standalone or include the other plugins to do so

I have tried with those plugins. I notice in the babel documentation is mentions that the order of plugins does matter. Can you tell me what the order should be? I will try again when I get home.

Here is a .babelrc that works for doing things like

const store = createStore(
  combineReducers({
    ...reducers,
    routing: routerReducer
  })
)

.babelrc

{
  "presets": ["react", "es2015"],
  "plugins": ["transform-es2015-destructuring", "transform-object-rest-spread"]
}

You can install the two plugins with:

npm install --save-dev babel-plugin-transform-es2015-destructuring

&

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

As @janzenz mentioned for me adding stage-0 worked I did not need transform-object-rest-spread and transform-es2015-destructuring

{ "presets": ["react", "es2015", "stage-0"] }

You didn't need them because you are already using the es2015 preset.

I'd recommend staying away from stage-0; use stage-3, which also includes this feature, but includes less features that have a high risk of changing dramatically.

EDIT: better / more up-to-date advice: don't use any preset besides env, react or flow (should you use either of their features); avoid yearly or stage presets. If you need to use an experimental feature that's not supported by those 3 presets, use its plugin directly.

Agreed with @Kovensky, I started a project about 2 months ago installing stage-0. I changed laptops recently and after npm install the stage-0 gave me massive issues with spread operator.

For me @kareniel answer fixed the issue.

@Kovensky Thank you!

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

Still not working using the env or es2017 preset

@micky2be the same for me. Did you find out a solution? Thx.

env and es2017 do not contain object rest spread. Object-rest-spread is still an experimental feature which not yet finished the specification process.
If you want to use it install babel-preset-stage-3 or the plugin itself.
see @kareniel s comment above

Yeah, realized that. Got used to Typescript where everything works.
I'm using stage-0 now

tried the stage-3 preset, but it still does not work for me.

            use: [{
                loader: 'babel-loader',
                options: {
                    "sourceMaps": "inline",
                    presets: [
                        ['react', "node7", "stage-3",
                            { modules: false }]
                    ]
                }

Using es7 plugins not working for me too. Jest results with an error when I use spread rest:

TypeError: /Users/ufukomer/nmobs/tagon-dashboard/client/models/campaigns.js: Property property of MemberExpression expected node to be of a type ["Identifier"] but instead got null

screen shot 2017-07-05 at 11 38 57 am

Btw, I also can not see the exact error line

I had a similar issue. I am using package.json to define my plugins and presets.
"babel": { "presets": [ "env"], "plugins": [] }
I found that the .babelrc was overwriting everything I entered in package.json. Once I deleted the .babelrc file, the "env" preset alone fixed my issue of using spread syntax.

Good Job!!!

For the life of me, I can't figure out how to get babel to transpile the rest/spread operator.
.babelrc --

{
  "presets": ["env"],
  "plugins": ["transform-es2015-destructuring", "transform-object-rest-spread"]
}

code --

this.state = newStateArray.reduce((newState, stateEntry)=> (
       {
         ...newState,
         stateEntry[0]: stateEntry[1]
       }
      ), this.state
     )

Error --

Message:
    /Users/ericfoster/Documents/Developer/Javascript/Valence/js/src/Component.js: Unexpected token, expected , (53:19)

In addition to the current .babelrc configuration, I've experimented with every preset/plugin combination I could think of. I've tried stage-0, stage-2, stage-3, react, es2015+ presets and at this point am out of ideas.

@ejames9 stateEntry[0]: stateEntry[1] is a syntax error . Are you looking for [stateEntry[0]]: stateEntry[1]?

Holy Crap! I absolutely was having trouble with the spread property, but I didn't notice when the problem was solved because I had a syntax error in nearly the same spot! AArgh! Thank you sooo very much for pointing that out!:) I realize this isn't stack overflow, but could you by chance tell me why that is a syntax error? Your suggestion solved my problem, but I guess I don't understand why the key needs square brackets in this case? Any clarification would be much appreciated! Thanks again!

An object requires the keys to be strings and stateEntry would be a valid key but stateEntry[0] is a value so you need to wrap it in [] for it to be a computed property like in https://babeljs.io/docs/plugins/transform-es2015-computed-properties/.

So, if, for instance:

stateEntry = ['foo', 9]

Would the key that I'm adding to the object be 'foo', or [stateEntry[0]]? Does the key stay unresolved?

It's the same thing as doing a[stateEntry[0]] = stateEntry[1]; if a is the new object but it's "inlined" in that object literal

FYI In the future I would suggest you can ask these kinds of questions on our slack or stackoverflow

As I stated above "I realize this is not stack overflow". If answering my question is a waste of your time, then don't answer it. My original purpose was to report a bug. It turns out I made a mistake, as we all, I'm sure you included, do. Thank you for the info you've given. It was helpful.

My conscience got the better of me, sorry for being snippy. You're right, I know better than to ask those kinds of questions here. Thanks again, though for your explanation, it really did help out a lot!

.babelrc file & two plugins [babel-plugin-transform-es2015-destructuring & babel-plugin-transform-object-rest-spread] working for me problem solved.

good job

Tried every solution mentioned above and none of them works for me:

37:21 is on { at return [{...array[i]}]
``` ERROR in ./ClientApp/services/utils.js
Module parse failed: D:\D\Projekty\QR\SimpleCQRS\SampleCQRS\QR.Web\ClientApp\services\utils.js Unexpected token (37:21)
You may need an appropriate loader to handle this file type.
| for (let i = 0; i < array.length; i++) {
| if (array[i].name === name) {
| return [{...array[i]}]
| }
| let a = this.findInNestedByName(array[i].children, name)
@ ./ClientApp/store/getters.js 1:0-34
@ ./ClientApp/store/index.js
@ ./ClientApp/main.js

.babelrc:
```{
  "presets": [
    [
      "env",
      {
        "modules": false
      }
    ],
    "stage-2"
  ],
  "plugins": ["transform-runtime","transform-es2015-destructuring", "transform-object-rest-spread"],
  "comments": false,
  "env": {
    "test": {
      "plugins": [ "istanbul" ]
    }
  }
}

Something else I should do or can provide?

To clarify, object-rest-spread is still a proposal, and right now is a stage 4 proposal, so that's why it isn't in babel-preset-env and we need the plugin?

I thought that all the spread operator usages were in the same stage (or same proposal). It's weird that we can use spread/rest in arrays and fns but in objects not.. I thought that the spread operator worked on any iterable (that cover objects)...

Things that are stage-4 are no longer proposals -- they _are_ part of the language.

It not being in babel-preset-env is because the preset hasn't been updated yet. The babel 7 version (@babel/preset-env) supports a shippedProposals option that will enable it; the missing update is to have it enabled by default instead of enabled by shippedProposals.

Facing the same problem, tried all the above suggestions. Nothing worked. Is there any perfect solution to this problem?

I am also facing same issue.

Added stage-0 by yarn add babel-preset-stage-0 and changed the .babelrc to

{
  "presets": ["react", "es2015", "stage-0"],
}

worked for me. Thanks @StevenIseki :)

If you're using @babel/preset-env you'll need

npm i -D @babel/plugin-transform-destructuring @babel/plugin-proposal-object-rest-spread

This totally worked for me

on command line:
yarn add babel-transform-object-rest-spread -D

inside file .babelrc:

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

For future queriers:

on command line:
yarn add babel-transform-object-rest-spread -D

If you're going that route, the package is now called babel-plugin-transform-object-rest-spread. Also worked for me.

the same problem, consume me a lot of time

This might help anyone coming around this issue, using babel 7:
https://babeljs.io/docs/en/babel-preset-stage-0
https://babeljs.io/blog/2018/07/27/removing-babels-stage-presets

As mentioned before, I believe that @babel/plugin-proposal-object-rest-spread is the solution 馃憤

thanks @kareniel and others for the advise. it's working now in my end.

2020 solution: make sure you're using Babel 7 (@babel/core), not 6 (babel-core)

In my case upgrading npm from v8.0.0 to v8.7.0 solved the issue, nothing else helped from the mentioned suggestions.

In my case upgrading npm from v8.0.0 to v8.7.0 solved the issue, nothing else helped from the mentioned suggestions.

@ansisblodnieks As far as I know there is no npm version 8, version 7 was just released. Do you mean node 8 (which is no longer supported, the latest version being 8.17.0 that comes with npm 5)?

Was this page helpful?
0 / 5 - 0 ratings