rails / jsbundling-rails

Bundle and transpile JavaScript in Rails with esbuild, rollup.js, or Webpack.
MIT License
831 stars 143 forks source link

Import application JS as a module #178

Closed afcapel closed 8 months ago

afcapel commented 9 months ago

The default javascript_include_tag added to application.html.erbhas type='text/javascript', which can cause problems when the bundler output is in ESM format. If the bundler outputs ESM code, we need to import it with type="module". Otherwise the module varibles end up in the global scope. See https://github.com/hotwired/turbo/pull/1077

This is especially problematic for bun.js, because bun can only emit ESM code at the moment.

This PR updates the install generator to add the type="module" attribute to the default javascript_include_tag.

defer is no longer needed, as JS modules are deferred by default.

Ref. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules#other_differences_between_modules_and_standard_scripts

This PR also updates the default config to ensure that all bundlers output ESM bundles.

psantos10 commented 9 months ago

I can confirm, adding type="module" fixes the problem:

<%= javascript_include_tag "application", "data-turbo-track": "reload", type: "module" %>