Rails asset pipeline: Using ESNext without a transpiler

Updated . Posted . Visible to the public.

If your app does not need to support IE11, you can use most ES6 features without a build step. Just deliver your plain JavaScript without transpilation through Babel or TypeScript, and modern browsers will run them natively.

Features supported by all modern browsers include:

  • fat arrow functions (() => { expr })
  • let / const
  • class
  • async / await
  • Promises
  • Generators
  • Symbols
  • Rest arguments (...args)
  • Destructuring

You won't be able to use import and export, or use npm modules.

See this ES6 compatibility matrix for details.

ES6 and Uglifier

If you're using Rails with the assets pipeline Show archive.org snapshot (sprockets) you are probably using Uglifier to minify your JavaScript.

Uglifier can minify some, but not all ES6 language features.

Check if you're affected

You can check if that's an issue for your project by running bundle exec rails assets:precompile in your development environment (don't forget to run bundle exec assets:clobber afterwards).

You might get one of these errors:

The asset "application.js" is not present in the asset pipeline. [...]

Uglifier::Error: Unexpected token operator «=», expected punc «,». To use ES6 syntax, harmony mode must be enabled with Uglifier.new(:harmony => true).

If you're encountering a build error, use one of the workarounds below.

Workaround: Use terser-ruby instead

The terser Show archive.org snapshot gem can minify most ES6 features.

To use this gem you also need to upgrade your sprockets dependency to >= 3.

Afterwards you can use terser-ruby as your minifyer:

config.assets.js_compressor = Terser.new

Workaround: Harmony mode for Uglifier

Uglifier has a "harmony" mode in which it can minify some, but not all ES6 features.

To activate this replace the following line in your staging and production environments:

- config.assets.js_compressor = :uglifier
+ config.assets.js_compressor = Uglifier.new(harmony: true)
Henning Koch
Last edit
Jonas Schiele
Keywords
table
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2019-01-07 19:09)