Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Import application JS as a module #178

Merged
merged 1 commit into from
Jan 5, 2024
Merged

Conversation

afcapel
Copy link
Contributor

@afcapel afcapel commented Nov 27, 2023

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 hotwired/turbo#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
Copy link

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

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

Bun.js generates JS bundles in the ESM format and they need be imported with
the `type="module"` attribute. Otherwise the module varibles end up in the
global scope. See hotwired/turbo#1077

This commit 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 are
configured to output ESM bundles.

- bun only supports ESM at the moment https://bun.sh/docs/bundler#format
- esbuild is configured to output ESM with the --format=esm flag https://esbuild.github.io/api/#format-esm
- webpacker is configured to output ESM bundles with `output.chunkFormat` https://webpack.js.org/configuration/output/#outputchunkformat
- rollup is configured to output ESM bundles with `output.format` https://rollupjs.org/configuration-options/#output-format
@dhh dhh merged commit 880a1bd into rails:main Jan 5, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants