Search code examples
ruby-on-railscoffeescriptruby-on-rails-5asset-pipeline

Coffeescript is not being compiled correctly in rails with async and await syntax


i have a similar coffee-script like this in my assets/javascript directory

#COFFEE SCRIPT CODE
class TestClass
  speak: ()->
    response = await fetch(location.url)
    console.log(response)

its being compiled correctly with proper async/await syntax in coffee-script's official playground

# COMPILED JS FROM COFFEESCRIPT OFFICIAL PLAYGROUND
var TestClass;

TestClass = class TestClass {
  async speak() {
    var response;
    response = (await fetch(location.url));
    return console.log(response);
  }

};

but when i write this in a file and make it compile through assets pipeline it get compiled incorrectly

# COMPILED JS FROM COFFEESCRIPT ASSESTS PIPELINE
TestClass = (function() {
    function TestClass() {}

    TestClass.prototype.speak = function() {
      var response;
      response = await(fetch(location.url));
      return console.log(response);
    };

    return TestClass;

  })();

i am on rails v5.2 and ruby v2.6.4 on macOS v10.14

$ bundle info coffee-script
      * coffee-script (2.4.1)
            Summary: Ruby CoffeeScript Compiler
            Homepage: http://github.com/josh/ruby-coffee-script
            Path: /Users/<username>/.rvm/gems/ruby-2.6.4/gems/coffee-script-2.4.1

my gemlock file

why is this happening and how to fix it.

i need the proper async/await syntax via my assests pipeline


Solution

  • Unfortunately the coffee-rails gem doesn't use the most up-to-date version of CoffeeScript and is thus missing some of the ES2017 features like await that you're looking for.

    coffee-rails itself depends on the coffee-script-source gem which you can see is still using CoffeeScript v1.12.6:

    # https://github.com/jessedoyle/coffee-script-source/blob/master/src/js/coffee-script.js
    
    /**
     * CoffeeScript Compiler v1.12.6
     * http://coffeescript.org
     *
     * Copyright 2011, Jeremy Ashkenas
     * Released under the MIT License
     */