ecmascript-6es6-modulesruby-on-rails-7sprocketsrails-sprockets

Is it possible to set type=module on javascript_include_tag in Rails 7 with Sprockets 4


I've been working on a migration project, upgrading Rails 5 to Rails 7. We decided to keep with Sprockets because it is a rather large application and moving over to the new toolset would create a lot more work than we can afford right now.

Everything seems to run fine (all the tests pass at least), but when I fire up the browser, I am getting this error message in the console:

Uncaught SyntaxError: Unexpected token 'export' which is coming from application.js

I read that this can be resolved by setting the type=module of the <script>.

Is that possible to do? I don't see anything in the documentation for the javascript_include_tag.

My understanding is that ES6 support is included in Sprockets 4, so I'm not sure why this is happening.


Solution

  • Any other specified options will be treated as HTML attributes for the script tag.

    https://api.rubyonrails.org/classes/ActionView/Helpers/AssetTagHelper.html#method-i-javascript_include_tag

    <%= javascript_include_tag "application.js", type: :module %>
    

    To transpile ES6 you need to add gem "babel-transpiler" and use .es6 extension instead of .js.

    https://github.com/rails/sprockets?tab=readme-ov-file#es6-support