Using the Object rest/spread operator in Ember

by Ryan Toronto

JavaScript's new spread syntax provides a concise way to combine two objects into a new POJO:

let a = { a: 1 }
let b = { b: 2 }
let c = { ...a, ...b } // => { a: 1, b: 2 }

(If you're familiar with Redux, this pattern is commonly used to return a new state object from a reducer.)

Recently I tried using the spread operator in an Ember app, but as soon as I did I got a build error because of invalid syntax.

It turns out Ember CLI doesn't support the object rest/spread syntax out of the box – and for good reason! Ember CLI only targets the current version of JavaScript, and the object rest/spread operator is currently a stage 3 proposal. Stage 3 proposals are very likely to make it into the language, but they aren't official yet. Ember CLI had to draw the line somewhere, and it made the decision to only support new features that had made it to stage 4.

Fortunately, Ember CLI makes it extremely easy to enable these experimental features. Here's what I did to enable the object rest/spread operator in our codebase.

  1. Install the babel plugin:

     npm install --save-dev babel-plugin-transform-object-rest-spread
  2. Tell Ember CLI to load the plugin:

     // ember-cli-build.js
     var app = new EmberApp(defaults, {
       babel: {
         plugins: ['transform-object-rest-spread']
  3. Finally, add experimentalObjectRestSpread to the ESLint config to avoid editor warnings:

     // .eslintrc.js
     module.exports = {
       // ...
       parserOptions: {
         ecmaVersion: 2017,
         sourceType: 'module',
         ecmaFeatures: {
           experimentalObjectRestSpread: true
      // ...

Thats it! You can now use the object rest/spread operator in your Ember code.


Send us a tweet:

Or ask us in Inside EmberMap, our private Slack workspace for subscribers.