importmap-rails 0.8.0 → 2.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 5ff9e12c3e3daaf05a7de52415d5147fc030efd2ad0cd170eb60a13c0227bb72
4
- data.tar.gz: '09d07386cd7f80d6f34d369e530276125e6a5361577896bc847d7968a9f158a6'
3
+ metadata.gz: e86788c54e7b80120cf17b2df4f51a02f03e8b40356bb2f8abad069639b763a0
4
+ data.tar.gz: 4e29f8b3e0cacb49f7d379b2536e736acb015f2b9b55a7fdfa97cfb83ccdf916
5
5
  SHA512:
6
- metadata.gz: 5be65a22e79a2d7bff6b317d1a162dbdc9be2f0fb05449c7675a6c9583a2b578e2e07265bf9fefa1a404a92053dd02f019d705b5b2793184f5e35f28b48a1235
7
- data.tar.gz: 32875269eb69d4b1fed15d6d93831dae419354b13e46b2a0edb26b041b403f6e77f4f95169955aa8cda540c8d3d253f49ab0fd2a1a6b8b43e8313a947943ae12
6
+ metadata.gz: 48ebde452587115deed3ab2f6a2dbcc777eb15bde84feb76cc77d12e884f22557a6131c584e60a4cfcb19a031e131f83fcc78a7fbfc21dbeb7625543d40f7600
7
+ data.tar.gz: d5f5992507d837c9de40bc88af8776c73150a6fbb628264b96dd6895ee50eb5692776a28f4ff9239e90894a803a59617f370c213a96beacec67a2a0dcc31689a
data/MIT-LICENSE CHANGED
@@ -1,4 +1,4 @@
1
- Copyright (c) 2021 Basecamp
1
+ Copyright (c) 2022 Basecamp
2
2
 
3
3
  Permission is hereby granted, free of charge, to any person obtaining
4
4
  a copy of this software and associated documentation files (the
data/README.md CHANGED
@@ -1,169 +1,269 @@
1
1
  # Importmap for Rails
2
2
 
3
- [Import maps](https://github.com/WICG/import-maps) let you import JavaScript modules using logical names that map to versioned/digested files – directly from the browser. So you can [build modern JavaScript applications using JavaScript libraries made for ESM without the need for transpiling or bundling](https://world.hey.com/dhh/modern-web-apps-without-javascript-bundling-or-transpiling-a20f2755).This frees you from needing Webpack, Yarn, npm, or any other part of the JavaScript toolchain. All you need is the asset pipeline that's already included in Rails.
3
+ [Import maps](https://github.com/WICG/import-maps) let you import JavaScript modules using logical names that map to versioned/digested files – directly from the browser. So you can [build modern JavaScript applications using JavaScript libraries made for ES modules (ESM) without the need for transpiling or bundling](https://world.hey.com/dhh/modern-web-apps-without-javascript-bundling-or-transpiling-a20f2755). This frees you from needing Webpack, Yarn, npm, or any other part of the JavaScript toolchain. All you need is the asset pipeline that's already included in Rails.
4
4
 
5
- With this approach you'll ship many small JavaScript files instead of one big JavaScript file. Thanks to HTTP/2 that no longer carries a material performance penalty during the initial transport, and in fact offers substantial benefits over the long run due to better caching dynamics. Whereas before any change to any JavaScript file included in your big bundle would invalidate the cache for the the whole bundle, now only the cache for that single file is invalidated.
5
+ With this approach you'll ship many small JavaScript files instead of one big JavaScript file. Thanks to HTTP/2 that no longer carries a material performance penalty during the initial transport, and in fact offers substantial benefits over the long run due to better caching dynamics. Whereas before any change to any JavaScript file included in your big bundle would invalidate the cache for the whole bundle, now only the cache for that single file is invalidated.
6
6
 
7
- There's [native support for import maps in Chrome/Edge 89+](https://caniuse.com/?search=importmap), and [a shim available](https://github.com/guybedford/es-module-shims) for any browser with basic ESM support. So your app will be able to work with all the evergreen browsers.
7
+ [Import maps are supported natively in all major, modern browsers](https://caniuse.com/?search=importmap). If you need to work with legacy browsers without native support, you can explore using [the shim available](https://github.com/guybedford/es-module-shims).
8
8
 
9
9
 
10
10
  ## Installation
11
11
 
12
- Importmap for Rails is automatically included in Rails 7+ for new applications, but you can also install it manually in existing applications:
12
+ Importmap for Rails is automatically included in Rails 7+ for new applications, but you can also install it manually in existing applications:
13
13
 
14
- 1. Add `importmap-rails` to your Gemfile with `gem 'importmap-rails'`
15
- 2. Run `./bin/bundle install`
16
- 3. Run `./bin/rails importmap:install`
14
+ 1. Run `./bin/bundle add importmap-rails`
15
+ 2. Run `./bin/rails importmap:install`
17
16
 
18
17
  Note: In order to use JavaScript from Rails frameworks like Action Cable, Action Text, and Active Storage, you must be running Rails 7.0+. This was the first version that shipped with ESM compatible builds of these libraries.
19
18
 
19
+ You can pin those libraries manually by relying on the compiled versions included in Rails like this:
20
+
21
+ ```ruby
22
+ pin "@rails/actioncable", to: "actioncable.esm.js"
23
+ pin "@rails/activestorage", to: "activestorage.esm.js"
24
+ pin "@rails/actiontext", to: "actiontext.esm.js"
25
+ pin "trix"
26
+ ```
27
+
28
+ ## How do importmaps work?
29
+
30
+ At their core, importmaps are essentially a string substitution for what are referred to as "bare module specifiers". A "bare module specifier" looks like this: `import React from "react"`. This is not compatible with the ES Module loader spec. Instead, to be ESM compatible, you must provide 1 of the 3 following types of specifiers:
31
+
32
+ - Absolute path:
33
+ ```js
34
+ import React from "/Users/DHH/projects/basecamp/node_modules/react"
35
+ ```
36
+
37
+ - Relative path:
38
+ ```js
39
+ import React from "./node_modules/react"
40
+ ```
41
+
42
+ - HTTP path:
43
+ ```js
44
+ import React from "https://ga.jspm.io/npm:react@17.0.1/index.js"
45
+ ```
46
+
47
+ Importmap-rails provides a clean API for mapping "bare module specifiers" like `"react"`
48
+ to 1 of the 3 viable ways of loading ES Module javascript packages.
49
+
50
+ For example:
51
+
52
+ ```rb
53
+ # config/importmap.rb
54
+ pin "react", to: "https://ga.jspm.io/npm:react@17.0.2/index.js"
55
+ ```
56
+
57
+ means "every time you see `import React from "react"`
58
+ change it to `import React from "https://ga.jspm.io/npm:react@17.0.2/index.js"`"
59
+
60
+ ```js
61
+ import React from "react"
62
+ // => import React from "https://ga.jspm.io/npm:react@17.0.2/index.js"
63
+ ```
20
64
 
21
65
  ## Usage
22
66
 
23
67
  The import map is setup through `Rails.application.importmap` via the configuration in `config/importmap.rb`. This file is automatically reloaded in development upon changes, but note that you must restart the server if you remove pins and need them gone from the rendered importmap or list of preloads.
24
68
 
25
- This import map is inlined in the `<head>` of your application layout using `<%= javascript_importmap_tags %>`, which will setup the JSON configuration inside a `<script type="importmap">` tag. After that, the [es-module-shim](https://github.com/guybedford/es-module-shims) is loaded, and then finally the application entrypoint is imported via `<script type="module">import "application"</script>`. That logical entrypoint, `application`, is mapped in the importmap script tag to the file `app/javascript/application.js`.
69
+ This import map is inlined in the `<head>` of your application layout using `<%= javascript_importmap_tags %>`, which will setup the JSON configuration inside a `<script type="importmap">` tag. Then the application entrypoint is imported via `<script type="module">import "application"</script>`. That logical entrypoint, `application`, is mapped in the importmap script tag to the file `app/javascript/application.js`.
26
70
 
27
71
  It's in `app/javascript/application.js` you setup your application by importing any of the modules that have been defined in the import map. You can use the full ESM functionality of importing any particular export of the modules or everything.
28
72
 
29
73
  It makes sense to use logical names that match the package names used by npm, such that if you later want to start transpiling or bundling your code, you won't have to change any module imports.
30
74
 
75
+ ### Local modules
31
76
 
32
- ## Using npm packages via JavaScript CDNs
77
+ If you want to import local js module files from `app/javascript/src` or other sub-folders of `app/javascript` (such as `channels`), you must pin these to be able to import them. You can use `pin_all_from` to pick all files in a specific folder, so you don't have to `pin` each module individually.
33
78
 
34
- Importmap for Rails is designed to be used with JavaScript CDNs for your npm package dependencies. The CDNs provide pre-compiled distribution versions ready to use, and offer a fast, efficient way of serving them.
79
+ ```rb
80
+ # config/importmap.rb
81
+ pin_all_from 'app/javascript/src', under: 'src', to: 'src'
35
82
 
36
- You can use the `./bin/importmap` command that's added as part of the install to pin, unpin, or update npm packages in your import map. This command uses an API from [JSPM.org](https://jspm.org) to resolve your package dependencies efficiently, and then add the pins to your `config/importmap.rb` file. It can resolve these dependencies from JSPM itself, but also from other CDNs, like [unpkg.com](https://unpkg.com) and [jsdelivr.com](https://www.jsdelivr.com).
83
+ # With automatic integrity calculation for enhanced security
84
+ enable_integrity!
85
+ pin_all_from 'app/javascript/controllers', under: 'controllers', integrity: true
86
+ ```
37
87
 
38
- It works like so:
88
+ The `:to` parameter is only required if you want to change the destination logical import name. If you drop the :to option, you must place the :under option directly after the first parameter.
39
89
 
40
- ```bash
41
- ./bin/importmap pin react react-dom
42
- Pinning "react" to https://ga.jspm.io/npm:react@17.0.2/index.js
43
- Pinning "react-dom" to https://ga.jspm.io/npm:react-dom@17.0.2/index.js
44
- Pinning "object-assign" to https://ga.jspm.io/npm:object-assign@4.1.1/index.js
45
- Pinning "scheduler" to https://ga.jspm.io/npm:scheduler@0.20.2/index.js
90
+ The `enable_integrity!` call enables integrity calculation globally, and `integrity: true` automatically calculates integrity hashes for all files in the directory, providing security benefits without manual hash management.
46
91
 
47
- ./bin/importmap json
92
+ Allows you to:
48
93
 
49
- {
50
- "imports": {
51
- "application": "/assets/application-37f365cbecf1fa2810a8303f4b6571676fa1f9c56c248528bc14ddb857531b95.js",
52
- "react": "https://ga.jspm.io/npm:react@17.0.2/index.js",
53
- "react-dom": "https://ga.jspm.io/npm:react-dom@17.0.2/index.js",
54
- "object-assign": "https://ga.jspm.io/npm:object-assign@4.1.1/index.js",
55
- "scheduler": "https://ga.jspm.io/npm:scheduler@0.20.2/index.js"
56
- }
57
- }
94
+ ```js
95
+ // app/javascript/application.js
96
+ import { ExampleFunction } from 'src/example_function'
58
97
  ```
98
+ Which imports the function from `app/javascript/src/example_function.js`.
59
99
 
60
- As you can see, the two packages react and react-dom resolve to a total of four dependencies, when resolved via the jspm default.
100
+ Note: Sprockets used to serve assets (albeit without filename digests) it couldn't find from the `app/javascripts` folder with logical relative paths, meaning pinning local files wasn't needed. Propshaft doesn't have this fallback, so when you use Propshaft you have to pin your local modules.
61
101
 
62
- Now you can use these in your application.js entrypoint like you would any other module:
102
+ ## Using npm packages via JavaScript CDNs
63
103
 
64
- ```js
65
- import React from "react"
66
- import ReactDOM from "react-dom"
67
- ```
104
+ Importmap for Rails downloads and vendors your npm package dependencies via JavaScript CDNs that provide pre-compiled distribution versions.
68
105
 
69
- You can also designate a specific version to pin:
106
+ You can use the `./bin/importmap` command that's added as part of the install to pin, unpin, or update npm packages in your import map. By default this command uses an API from [JSPM.org](https://jspm.org) to resolve your package dependencies efficiently, and then add the pins to your `config/importmap.rb` file.
70
107
 
71
108
  ```bash
72
- ./bin/importmap pin react@17.0.1
73
- Pinning "react" to https://ga.jspm.io/npm:react@17.0.1/index.js
74
- Pinning "object-assign" to https://ga.jspm.io/npm:object-assign@4.1.1/index.js
109
+ ./bin/importmap pin react
110
+ Pinning "react" to vendor/javascript/react.js via download from https://ga.jspm.io/npm:react@19.1.0/index.js
75
111
  ```
76
112
 
77
- Or even remove pins:
113
+ This will produce a pin in your `config/importmap.rb` like so:
78
114
 
79
- ```bash
80
- ./bin/importmap unpin react
81
- Unpinning "react"
82
- Unpinning "object-assign"
115
+ ```ruby
116
+ pin "react" # @19.1.0
83
117
  ```
84
118
 
85
- If you pin a package that has already been pinned, it'll be updated inline, along with its dependencies.
119
+ Other CDNs like [unpkg.com](https://unpkg.com) and [jsdelivr.com](https://www.jsdelivr.com) can be specified with `--from`:
86
120
 
87
- You can control the environment of the package for packages with separate "production" (the default) and "development" builds:
121
+ ```bash
122
+ ./bin/importmap pin react --from unpkg
123
+ Pinning "react" to vendor/javascript/react.js via download from https://unpkg.com/react@19.1.0/index.js
124
+ ```
88
125
 
89
126
  ```bash
90
- ./bin/importmap pin react --env development
91
- Pinning "react" to https://ga.jspm.io/npm:react@17.0.2/dev.index.js
92
- Pinning "object-assign" to https://ga.jspm.io/npm:object-assign@4.1.1/index.js
127
+ ./bin/importmap pin react --from jsdelivr
128
+ Pinning "react" to vendor/javascript/react.js via download from https://cdn.jsdelivr.net/npm/react@19.1.0/index.js
93
129
  ```
94
130
 
95
- You can also pick an alternative, supported CDN provider when pinning, like `unpkg` or `jsdelivr` (`jspm` is the default):
131
+ The packages are downloaded to `vendor/javascript`, which you can check into your source control, and they'll be available through your application's own asset pipeline serving.
132
+
133
+ If you later wish to remove a downloaded pin:
96
134
 
97
135
  ```bash
98
- ./bin/importmap pin react --from jsdelivr
99
- Pinning "react" to https://cdn.jsdelivr.net/npm/react@17.0.2/index.js
136
+ ./bin/importmap unpin react
137
+ Unpinning and removing "react"
100
138
  ```
101
139
 
102
- Remember, though, that if you switch a pin from one provider to another, you may have to clean up dependencies added by the first provider that isn't used by the second provider.
140
+ ## Subresource Integrity (SRI)
103
141
 
104
- Run `./bin/importmap` to see all options.
142
+ For enhanced security, importmap-rails supports [Subresource Integrity (SRI)](https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity) hashes for packages loaded from external CDNs.
105
143
 
106
- Note that this command is merely a convenience wrapper to resolving logical package names to CDN URLs. You can also just lookup the CDN URLs yourself, and then pin those. For example, if you wanted to use Skypack for React, you could just add the following to `config/importmap.rb`:
144
+ ### Automatic integrity for local assets
145
+
146
+ To enable automatic integrity calculation for local assets served by the Rails asset pipeline, you must first call `enable_integrity!` in your importmap configuration:
107
147
 
108
148
  ```ruby
109
- pin "react", to: "https://cdn.skypack.dev/react"
149
+ # config/importmap.rb
150
+
151
+ # Enable integrity calculation globally
152
+ enable_integrity!
153
+
154
+ # With integrity enabled, these will auto-calculate integrity hashes
155
+ pin "application" # Auto-calculated integrity
156
+ pin "admin", to: "admin.js" # Auto-calculated integrity
157
+ pin_all_from "app/javascript/controllers", under: "controllers" # Auto-calculated integrity
158
+
159
+ # Mixed usage - explicitly controlling integrity
160
+ pin "cdn_package", integrity: "sha384-abc123..." # Pre-calculated hash
161
+ pin "no_integrity_package", integrity: false # Explicitly disable integrity
162
+ pin "nil_integrity_package", integrity: nil # Explicitly disable integrity
110
163
  ```
111
164
 
165
+ This is particularly useful for:
166
+ * **Local JavaScript files** managed by your Rails asset pipeline
167
+ * **Bulk operations** with `pin_all_from` where calculating hashes manually would be tedious
168
+ * **Development workflow** where asset contents change frequently
112
169
 
113
- ## Downloading vendor files from the JavaScript CDN
170
+ **Note:** Integrity calculation is opt-in and must be enabled with `enable_integrity!`. This behavior can be further controlled by setting `integrity: false` or `integrity: nil` on individual pins.
114
171
 
115
- If you don't want to use a JavaScript CDN in production, you can also download vendored files from the CDN when you're setting up your pins:
172
+ **Important for Propshaft users:** SRI support requires Propshaft 1.2+ and you must configure the integrity hash algorithm in your application:
116
173
 
117
- ```bash
118
- ./bin/importmap pin react --download
119
- Pinning "react" to vendor/react.js via download from https://ga.jspm.io/npm:react@17.0.2/index.js
120
- Pinning "object-assign" to vendor/object-assign.js via download from https://ga.jspm.io/npm:object-assign@4.1.1/index.js
174
+ ```ruby
175
+ # config/application.rb or config/environments/*.rb
176
+ config.assets.integrity_hash_algorithm = 'sha256' # or 'sha384', 'sha512'
121
177
  ```
122
178
 
123
- This will produce pins in your `config/importmap.rb` like so:
179
+ Without this configuration, integrity will be disabled by default when using Propshaft. Sprockets includes integrity support out of the box.
124
180
 
125
- ```ruby
126
- pin "react", to: "vendor/react.js" # https://ga.jspm.io/npm:react@17.0.2/index.js
127
- pin "object-assign", to: "vendor/object-assign.js" # https://ga.jspm.io/npm:object-assign@4.1.1/index.js
181
+ **Example output with `enable_integrity!` and `integrity: true`:**
182
+ ```json
183
+ {
184
+ "imports": {
185
+ "application": "/assets/application-abc123.js",
186
+ "controllers/hello_controller": "/assets/controllers/hello_controller-def456.js"
187
+ },
188
+ "integrity": {
189
+ "/assets/application-abc123.js": "sha256-xyz789...",
190
+ "/assets/controllers/hello_controller-def456.js": "sha256-uvw012..."
191
+ }
192
+ }
128
193
  ```
129
194
 
130
- The packages are downloaded to `app/javascript/vendor`, which you can check into your source control, and they'll be available through your application's own asset pipeline serving.
195
+ ### How integrity works
131
196
 
132
- If you later wish to remove a downloaded pin, you again pass `--download`:
197
+ The integrity hashes are automatically included in your import map and module preload tags:
133
198
 
134
- ```bash
135
- ./bin/importmap unpin react --download
136
- Unpinning and removing "react"
137
- Unpinning and removing "object-assign"
199
+ **Import map JSON:**
200
+ ```json
201
+ {
202
+ "imports": {
203
+ "lodash": "https://ga.jspm.io/npm:lodash@4.17.21/lodash.js",
204
+ "application": "/assets/application-abc123.js",
205
+ "controllers/hello_controller": "/assets/controllers/hello_controller-def456.js"
206
+ },
207
+ "integrity": {
208
+ "https://ga.jspm.io/npm:lodash@4.17.21/lodash.js": "sha384-PkIkha4kVPRlGtFantHjuv+Y9mRefUHpLFQbgOYUjzy247kvi16kLR7wWnsAmqZF"
209
+ "/assets/application-abc123.js": "sha256-xyz789...",
210
+ "/assets/controllers/hello_controller-def456.js": "sha256-uvw012..."
211
+ }
212
+ }
138
213
  ```
139
214
 
140
- Just like with a normal pin, you can also update a pin by running the `pin --download` command again.
215
+ **Module preload tags:**
216
+ ```html
217
+ <link rel="modulepreload" href="https://ga.jspm.io/npm:lodash@4.17.21/lodash.js" integrity="sha384-PkIkha4kVPRlGtFantHjuv+Y9mRefUHpLFQbgOYUjzy247kvi16kLR7wWnsAmqZF">
218
+ <link rel="modulepreload" href="/assets/application-abc123.js" integrity="sha256-xyz789...">
219
+ <link rel="modulepreload" href="/assets/controllers/hello_controller-def456.js" integrity="sha256-uvw012...">
220
+ ```
141
221
 
222
+ Modern browsers will automatically validate these integrity hashes when loading the JavaScript modules, ensuring the files haven't been modified.
142
223
 
143
224
  ## Preloading pinned modules
144
225
 
145
- To avoid the waterfall effect where the browser has to load one file after another before it can get to the deepest nested import, importmap-rails supports [modulepreload links](https://developers.google.com/web/updates/2017/12/modulepreload). Pinned modules can be preloaded by appending `preload: true` to the pin.
226
+ To avoid the waterfall effect where the browser has to load one file after another before it can get to the deepest nested import, importmap-rails uses [modulepreload links](https://developers.google.com/web/updates/2017/12/modulepreload) by default. If you don't want to preload a dependency, because you want to load it on-demand for efficiency, append `preload: false` to the pin.
146
227
 
147
228
  Example:
148
229
 
149
230
  ```ruby
150
231
  # config/importmap.rb
151
- pin "@github/hotkey", to: "https://ga.jspm.io/npm:@github/hotkey@1.4.4/dist/index.js", preload: true
152
- pin "md5", to: "https://cdn.jsdelivr.net/npm/md5@2.3.0/md5.js"
232
+ pin "@github/hotkey", to: "@github--hotkey.js" # file lives in vendor/javascript/@github--hotkey.js
233
+ pin "md5", preload: false # file lives in vendor/javascript/md5.js
153
234
 
154
235
  # app/views/layouts/application.html.erb
155
- <%= javascript_importmap_tags %>
236
+ <%= javascript_importmap_tags %>
156
237
 
157
238
  # will include the following link before the importmap is setup:
158
- <link rel="modulepreload" href="https://ga.jspm.io/npm:@github/hotkey@1.4.4/dist/index.js">
239
+ <link rel="modulepreload" href="/assets/javascript/@github--hotkey.js">
159
240
  ...
160
241
  ```
161
242
 
243
+ You can also specify which entry points to preload a particular dependency in by providing `preload:` a string or array of strings.
244
+
245
+ Example:
246
+
247
+ ```ruby
248
+ # config/importmap.rb
249
+ pin "@github/hotkey", to: "@github--hotkey.js", preload: 'application'
250
+ pin "md5", preload: ['application', 'alternate']
251
+
252
+ # app/views/layouts/application.html.erb
253
+ <%= javascript_importmap_tags 'alternate' %>
254
+
255
+ # will include the following link before the importmap is setup:
256
+ <link rel="modulepreload" href="/assets/javascript/md5.js">
257
+ ...
258
+ ```
259
+
260
+
261
+
162
262
  ## Composing import maps
163
263
 
164
264
  By default, Rails loads import map definition from the application's `config/importmap.rb` to the `Importmap::Map` object available at `Rails.application.importmap`.
165
265
 
166
- You can combine multiple import maps by drawing their definitions onto the `Rails.application.importmap`. For example, appending import maps defined in Rails engines:
266
+ You can combine multiple import maps by adding paths to additional import map configs to `Rails.application.config.importmap.paths`. For example, appending import maps defined in Rails engines:
167
267
 
168
268
  ```ruby
169
269
  # my_engine/lib/my_engine/engine.rb
@@ -171,8 +271,9 @@ You can combine multiple import maps by drawing their definitions onto the `Rail
171
271
  module MyEngine
172
272
  class Engine < ::Rails::Engine
173
273
  # ...
174
- initializer "my-engine.importmap", after: "importmap" do |app|
175
- app.importmap.draw(Engine.root.join("config/importmap.rb"))
274
+ initializer "my-engine.importmap", before: "importmap" do |app|
275
+ app.config.importmap.paths << Engine.root.join("config/importmap.rb")
276
+ # ...
176
277
  end
177
278
  end
178
279
  end
@@ -187,41 +288,88 @@ pin_all_from File.expand_path("../app/assets/javascripts", __dir__)
187
288
  ```
188
289
 
189
290
 
291
+ ## Selectively importing modules
292
+
293
+ You can selectively import your javascript modules on specific pages.
294
+
295
+ Create your javascript in `app/javascript`:
296
+
297
+ ```js
298
+ // /app/javascript/checkout.js
299
+ // some checkout specific js
300
+ ```
301
+
302
+ Pin your js file:
303
+
304
+ ```rb
305
+ # config/importmap.rb
306
+ # ... other pins...
307
+ pin "checkout", preload: false
308
+ ```
309
+
310
+ Import your module on the specific page. Note: you'll likely want to use a `content_for` block on the specific page/partial, then yield it in your layout.
311
+
312
+ ```erb
313
+ <% content_for :head do %>
314
+ <%= javascript_import_module_tag "checkout" %>
315
+ <% end %>
316
+ ```
317
+
318
+ **Important**: The `javascript_import_module_tag` should come after your `javascript_importmap_tags`
319
+
320
+ ```erb
321
+ <%= javascript_importmap_tags %>
322
+ <%= yield(:head) %>
323
+ ```
324
+
325
+
190
326
  ## Include a digest of the import map in your ETag
191
327
 
192
- If you're using [ETags](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag) generated by Rails helpers like `stale?` or `fresh_when`, you need to include the digest of the import map into this calculation. Otherwise your application will return 302 cache responses even when your JavaScript assets have changed. You can avoid this with something like:
328
+ If you're using [ETags](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag) generated by Rails helpers like `stale?` or `fresh_when`, you need to include the digest of the import map into this calculation. Otherwise your application will return [304](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/304) cache responses even when your JavaScript assets have changed. You can avoid this using the `stale_when_importmap_changes` method:
193
329
 
194
330
  ```ruby
195
331
  class ApplicationController < ActionController::Base
196
- etag { Rails.application.importmap.digest(resolver: helpers) if request.format&.html? }
332
+ stale_when_importmap_changes
197
333
  end
198
334
  ```
199
335
 
336
+ This will add the digest of the importmap to the etag calculation when the request format is HTML.
337
+
200
338
 
201
339
  ## Sweeping the cache in development and test
202
340
 
203
341
  Generating the import map json and modulepreloads may require resolving hundreds of assets. This can take a while, so these operations are cached, but in development and test, we watch for changes to both `config/importmap.rb` and files in `app/javascript` to clear this cache. This feature can be controlled in an environment configuration file via the boolean `config.importmap.sweep_cache`.
204
342
 
205
- If you're pinning local files from outside of `app/javascript`, you'll need to add them to the cache sweeper configuration or restart your development server upon changes to those external files. To add them to the configuration to clear the cache on changes, for instance when locally developing an engine, use an initializer like the following sample `config/initializers/importmap-caching.rb`:
343
+ If you're pinning local files from outside of `app/javascript`, you'll need to add them to the cache sweeper configuration or restart your development server upon changes to those external files. For example, here's how you can do it for Rails engine:
206
344
 
207
345
  ```ruby
208
- if Rails.env.development?
209
- Rails.application.importmap.cache_sweeper watches: [
210
- Rails.application.root.join("app/javascript"),
211
- MyEngine::Engine.root.join("app/assets/javascripts"),
212
- ]
346
+ # my_engine/lib/my_engine/engine.rb
347
+
348
+ module MyEngine
349
+ class Engine < ::Rails::Engine
350
+ # ...
351
+ initializer "my-engine.importmap", before: "importmap" do |app|
352
+ # ...
353
+ app.config.importmap.cache_sweepers << Engine.root.join("app/assets/javascripts")
354
+ end
355
+ end
213
356
  end
214
357
  ```
215
358
 
216
- ## Expected errors from using the es-module-shim
359
+ ## Checking for outdated or vulnerable packages
217
360
 
218
- While import maps are native in Chrome and Edge, they need a shim in other browsers that'll produce a JavaScript console error like `TypeError: Module specifier, 'application' does not start with "/", "./", or "../".`. This error is normal and does not have any user-facing consequences.
361
+ Importmap for Rails provides two commands to check your pinned packages:
362
+ - `./bin/importmap outdated` checks the NPM registry for new versions
363
+ - `./bin/importmap audit` checks the NPM registry for known security issues
219
364
 
220
- In Firefox. when opening the browser console, the asm.js module lexer build will run in unoptimized mode due to the debugger attaching. This gives a warning message `"asm.js type error: Disabled because no suitable wasm compiler is available"` which is as expected. When the console is closed again, the asm.js optimizations are fully applied, and this can even be verified with the console open by disabling the debugger in `about:config` and reloading the page.
365
+ ## Supporting legacy browsers such as Safari on iOS 15
221
366
 
222
- ## Turning off the shim
367
+ If you want to support [legacy browsers that do not support import maps](https://caniuse.com/import-maps) such as [iOS 15.8.1 released on 22 Jan 2024](https://support.apple.com/en-us/HT201222), insert [`es-module-shims`](https://github.com/guybedford/es-module-shims) before `javascript_importmap_tags` as below.
223
368
 
224
- Under certain circumstances, like running system tests using chromedriver under CI (which may be resource constrained and trigger errors in certain cases), you may want to explicitly turn off including the shim. You can do this by calling the bulk tag helper with `javascript_importmap_tags("application", shim: false)`. Thus you can pass in something like `shim: !ENV["CI"]`. If you want, and are sure you're not doing any full-page caching, you can also connect this directive to a user agent check (using a gem like `useragent`) to check whether the browser is chrome/edge 89+. But you really shouldn't have to, as the shim is designed to gracefully work with natively compatible drivers.
369
+ ```erb
370
+ <script async src="https://ga.jspm.io/npm:es-module-shims@1.8.2/dist/es-module-shims.js" data-turbo-track="reload"></script>
371
+ <%= javascript_importmap_tags %>
372
+ ```
225
373
 
226
374
  ## License
227
375
 
data/Rakefile CHANGED
@@ -3,8 +3,6 @@ require "bundler/setup"
3
3
  APP_RAKEFILE = File.expand_path("test/dummy/Rakefile", __dir__)
4
4
  load "rails/tasks/engine.rake"
5
5
 
6
- load "rails/tasks/statistics.rake"
7
-
8
6
  require "bundler/gem_tasks"
9
7
 
10
8
  require "rake/testtask"
@@ -0,0 +1,5 @@
1
+ module Importmap::Freshness
2
+ def stale_when_importmap_changes
3
+ etag { Rails.application.importmap.digest(resolver: helpers) if request.format&.html? }
4
+ end
5
+ end
@@ -1,54 +1,47 @@
1
1
  module Importmap::ImportmapTagsHelper
2
2
  # Setup all script tags needed to use an importmap-powered entrypoint (which defaults to application.js)
3
- def javascript_importmap_tags(entry_point = "application", shim: true)
3
+ def javascript_importmap_tags(entry_point = "application", importmap: Rails.application.importmap)
4
4
  safe_join [
5
- javascript_inline_importmap_tag,
6
- javascript_importmap_module_preload_tags,
7
- (javascript_importmap_shim_nonce_configuration_tag if shim),
8
- (javascript_importmap_shim_tag if shim),
5
+ javascript_inline_importmap_tag(importmap.to_json(resolver: self)),
6
+ javascript_importmap_module_preload_tags(importmap, entry_point:),
9
7
  javascript_import_module_tag(entry_point)
10
- ].compact, "\n"
8
+ ], "\n"
11
9
  end
12
10
 
13
11
  # Generate an inline importmap tag using the passed `importmap_json` JSON string.
14
12
  # By default, `Rails.application.importmap.to_json(resolver: self)` is used.
15
13
  def javascript_inline_importmap_tag(importmap_json = Rails.application.importmap.to_json(resolver: self))
16
14
  tag.script importmap_json.html_safe,
17
- type: "importmap", "data-turbo-track": "reload", nonce: content_security_policy_nonce
18
- end
19
-
20
- # Configure es-modules-shim with nonce support if the application is using a content security policy.
21
- def javascript_importmap_shim_nonce_configuration_tag
22
- if content_security_policy?
23
- tag.script({ nonce: content_security_policy_nonce }.to_json.html_safe,
24
- type: "esms-options", nonce: content_security_policy_nonce)
25
- end
26
- end
27
-
28
- # Include the es-modules-shim needed to make importmaps work in browsers without native support (like Firefox + Safari).
29
- def javascript_importmap_shim_tag(minimized: true)
30
- javascript_include_tag minimized ? "es-module-shims.min.js" : "es-module-shims.js",
31
- async: true, "data-turbo-track": "reload", nonce: content_security_policy_nonce
15
+ type: "importmap", "data-turbo-track": "reload", nonce: request&.content_security_policy_nonce
32
16
  end
33
17
 
34
18
  # Import a named JavaScript module(s) using a script-module tag.
35
19
  def javascript_import_module_tag(*module_names)
36
20
  imports = Array(module_names).collect { |m| %(import "#{m}") }.join("\n")
37
- tag.script imports.html_safe,
38
- type: "module", nonce: content_security_policy_nonce
21
+ tag.script imports.html_safe, type: "module", nonce: request&.content_security_policy_nonce
39
22
  end
40
23
 
41
24
  # Link tags for preloading all modules marked as preload: true in the `importmap`
42
25
  # (defaults to Rails.application.importmap), such that they'll be fetched
43
26
  # in advance by browsers supporting this link type (https://caniuse.com/?search=modulepreload).
44
- def javascript_importmap_module_preload_tags(importmap = Rails.application.importmap)
45
- javascript_module_preload_tag(*importmap.preloaded_module_paths(resolver: self))
27
+ def javascript_importmap_module_preload_tags(importmap = Rails.application.importmap, entry_point: "application")
28
+ packages = importmap.preloaded_module_packages(resolver: self, entry_point:, cache_key: entry_point)
29
+
30
+ _generate_preload_tags(packages) { |path, package| [path, { integrity: package.integrity }] }
46
31
  end
47
32
 
48
33
  # Link tag(s) for preloading the JavaScript module residing in `*paths`. Will return one link tag per path element.
49
34
  def javascript_module_preload_tag(*paths)
50
- safe_join(Array(paths).collect { |path|
51
- tag.link rel: "modulepreload", href: path, nonce: content_security_policy_nonce
52
- }, "\n")
35
+ _generate_preload_tags(paths) { |path| [path, {}] }
53
36
  end
37
+
38
+ private
39
+ def _generate_preload_tags(items)
40
+ content_security_policy_nonce = request&.content_security_policy_nonce
41
+
42
+ safe_join(Array(items).collect { |item|
43
+ path, options = yield(item)
44
+ tag.link rel: "modulepreload", href: path, nonce: content_security_policy_nonce, **options
45
+ }, "\n")
46
+ end
54
47
  end