Search code examples
ruby-on-railsuglifier

Rails Gem Uglifier 4.2 does not support async/await, how to fix


I have a Ruby on Rails project which uses some Javascript in the frontend. In development mode this runs fine, but when trying to build a Docker container (which compiles the assets) Uglifier gives an error Uglifier::Error: Unexpected token: operator (=). The offending code is:

var MyController = (function() {
    let self = undefined;
    MyController = class MyController {

        constructor() {
            self = this;
        }

        init() {...}
        ... // lots more code

        loadAsync = async (targetElement, num) => {       // <= this is the offending line
            await this.delay(5);
            $.ajax({
                url: `...`,
                method: 'GET',
                dataType: 'HTML',
                complete(response) {
                    ...
                }
            });
        };

        delay = ms => new Promise(res => setTimeout(res, ms));
     
        ... 

I know that Uglifier uses UglifyJS under the hood, and that this used to have problems with async/await. Are there versions available now that have this problem fixed, and if so, how do I install a working version? I use the newest Uglifier gem version available (4.2), using the options harmony: true, mangle: false.


Solution

  • The Uglifier readme says

    UglifyJS only works with ES5. If you need to compress ES6, ruby-terser is a better option.

    Switching to ruby-terser is an option. You could also use Babel to transpile ES6 into ES5.