Published

~1 minutes reading đź•‘

Thu, 01 February 2018

← Back to articles

How to use the JavaScript spread operator with Webpack

What is the Object Rest Spread operator?

One of the cool feature of JavaScript is the Object Rest Spread operator feature:

const preferences = {...defaultPreferences, ...savedPreferences};

Before this feature you could write it like that:

const preferences = Object.assign({}, defaultPreferences, savedPreferences);

Click here for more information about this Object Rest Spread feature.

Because it is still a stage 3 draft feature, webpack doesn't understand this operator yet and raise a Unexpected token parse error.

How to enable the draft feature with webpack

Parse failed: Unexpected token

ERROR in ./src/background/storage.js
Module parse failed: Unexpected token (54:28)
You may need an appropriate loader to handle this file type.
|       // set preferences defaults if not present
|       if (!Object.keys(preferences).length) {
|         preferences = {...defaultPreferences, ...savedPreferences};
|       }
 @ ./src/background.js

Babel to the rescue

The way to use experimental features in Javascript is to use Babel.

Hopefully for use there is a Babel plugin for this feature.

babel-loader and babel-plugin-transform-object-rest-spread to the rescue

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

Configure webpack

{
  module: {
    loaders: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
        query: {
          plugins:[ 'transform-object-rest-spread' ]
        }
      }
    ]
  }
}

Conclusion

This is a simple way to use this experimental feature with webpack.

Note that this will probably soon be unnecessary since webpack is implementing its support as we speak.

Revenir au début