importmap-plus 1.0.0
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 +7 -0
- data/CHANGELOG.md +46 -0
- data/MIT-LICENSE +20 -0
- data/README.md +457 -0
- data/Rakefile +17 -0
- data/app/controllers/importmap/freshness.rb +5 -0
- data/app/helpers/importmap/importmap_tags_helper.rb +47 -0
- data/lib/importmap/commands.rb +297 -0
- data/lib/importmap/engine.rb +73 -0
- data/lib/importmap/http_retries.rb +35 -0
- data/lib/importmap/map.rb +319 -0
- data/lib/importmap/minifier.rb +76 -0
- data/lib/importmap/npm.rb +189 -0
- data/lib/importmap/packager.rb +428 -0
- data/lib/importmap/reloader.rb +23 -0
- data/lib/importmap/version.rb +6 -0
- data/lib/importmap-plus.rb +4 -0
- data/lib/importmap-rails.rb +6 -0
- data/lib/install/bin/importmap +4 -0
- data/lib/install/config/importmap.rb +3 -0
- data/lib/install/install.rb +32 -0
- data/lib/tasks/importmap_tasks.rake +9 -0
- metadata +110 -0
checksums.yaml
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
---
|
|
2
|
+
SHA256:
|
|
3
|
+
metadata.gz: fea391704872c66da12c98d005e02ee2090282b4d7ce6065d46e6418ac4ca51e
|
|
4
|
+
data.tar.gz: a7bf185de0f21d3833eef1faa4d488b17f70779a744131033a1b74418c4ee194
|
|
5
|
+
SHA512:
|
|
6
|
+
metadata.gz: 2cf5e806291fd73a078b390e3cff8aeccd628cc61dfba53469081dec8951cde3a8380009ca9e7f0898c4a17b022ace9b7296f35576ffba0517ca57f2608ca42c
|
|
7
|
+
data.tar.gz: 13dc2bd3db6f202d60ad3752a33edcdd4e32a1e887cad34bc79f4eb5c9d54cb1582e9799f0af03d273309444b60c56bcba47e44057baf87af08464158b442ff4
|
data/CHANGELOG.md
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 1.0.0
|
|
4
|
+
|
|
5
|
+
First release of importmap-plus, a drop-in replacement for
|
|
6
|
+
[importmap-rails](https://github.com/rails/importmap-rails) 2.2.3. The
|
|
7
|
+
`Importmap::` API, the pin DSL and the generated import map are unchanged;
|
|
8
|
+
`Importmap::UPSTREAM_VERSION` names the importmap-rails release this tracks.
|
|
9
|
+
|
|
10
|
+
### Added
|
|
11
|
+
|
|
12
|
+
- **`bin/importmap pin --minify`** runs a download through bun, esbuild or
|
|
13
|
+
terser — the first found in `node_modules/.bin` or on `PATH`, including
|
|
14
|
+
Windows `.cmd` shims — before it lands in `vendor/javascript`. Always
|
|
15
|
+
transform-only, so bare import specifiers stay exactly as the CDN resolved
|
|
16
|
+
them and the import map keeps resolving them. `pristine --minify` does the
|
|
17
|
+
same for everything already vendored. Plenty of packages publish unminified
|
|
18
|
+
ESM (pdfjs-dist, choices.js, luxon), and a CDN serving package files
|
|
19
|
+
hands them out as published.
|
|
20
|
+
- **`--from esm.run`** pins jsDelivr's bundled builds instead of a package's
|
|
21
|
+
own dist file. A bundle references its dependencies as absolute
|
|
22
|
+
`/npm/dep@1.2.3/+esm` imports, which resolve only on jsDelivr; those are
|
|
23
|
+
rewritten to bare specifiers on download and each dependency without a pin
|
|
24
|
+
is vendored the same way. A dependency the app already pins is left alone,
|
|
25
|
+
so the bundle resolves to the version the app chose. Versions resolve
|
|
26
|
+
through jsDelivr's data API, so `pin luxon@3` and `pin apexcharts/core`
|
|
27
|
+
work as they do on npm.
|
|
28
|
+
- **Provenance in the pin comment.** A vendored pin records the CDN when it
|
|
29
|
+
isn't jspm and whether the file was minified — `pin "luxon" # @3.7.2
|
|
30
|
+
(esm.run, minified)`. `update`, `pristine` and a plain `pin` read it back,
|
|
31
|
+
so a package keeps its CDN and stays minified without repeating the flags.
|
|
32
|
+
This extends to every CDN: an unpkg download no longer silently moves back
|
|
33
|
+
to jspm on the next `update`.
|
|
34
|
+
- **An explicit `--from` moves a remote pin** to that CDN, instead of being
|
|
35
|
+
overruled by the provider the pin already points at.
|
|
36
|
+
- **Requests retry.** A reset connection, a timeout or a 429/5xx from the
|
|
37
|
+
CDN is tried up to three times with a growing pause before `bin/importmap`
|
|
38
|
+
gives up, and the failure then names the URL instead of a raw backtrace.
|
|
39
|
+
`Importmap::Packager.retry_attempts` / `retry_wait` tune it.
|
|
40
|
+
|
|
41
|
+
### Changed
|
|
42
|
+
|
|
43
|
+
- `bin/release` tags a version and publishes a GitHub Release, which fires
|
|
44
|
+
`.github/workflows/release.yml` to push the gem over RubyGems trusted
|
|
45
|
+
publishing. The upstream script pushed from a developer's machine with an
|
|
46
|
+
API key.
|
data/MIT-LICENSE
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
Copyright (c) 2022 Basecamp
|
|
2
|
+
|
|
3
|
+
Permission is hereby granted, free of charge, to any person obtaining
|
|
4
|
+
a copy of this software and associated documentation files (the
|
|
5
|
+
"Software"), to deal in the Software without restriction, including
|
|
6
|
+
without limitation the rights to use, copy, modify, merge, publish,
|
|
7
|
+
distribute, sublicense, and/or sell copies of the Software, and to
|
|
8
|
+
permit persons to whom the Software is furnished to do so, subject to
|
|
9
|
+
the following conditions:
|
|
10
|
+
|
|
11
|
+
The above copyright notice and this permission notice shall be
|
|
12
|
+
included in all copies or substantial portions of the Software.
|
|
13
|
+
|
|
14
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
|
15
|
+
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
|
16
|
+
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
|
17
|
+
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
|
18
|
+
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
|
19
|
+
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
|
20
|
+
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
data/README.md
ADDED
|
@@ -0,0 +1,457 @@
|
|
|
1
|
+
# importmap-plus
|
|
2
|
+
|
|
3
|
+
A drop-in replacement for [importmap-rails](https://github.com/rails/importmap-rails) with better vendoring: `bin/importmap pin --minify`, `--from esm.run` for jsDelivr's bundled builds, and a pin comment that remembers which CDN a package came from so later updates go back to it. Everything else is importmap-rails, constants included, so an app switches by changing one line in its `Gemfile`.
|
|
4
|
+
|
|
5
|
+
**Install this gem or importmap-rails, never both** — they define the same `Importmap::` constants and the same engine.
|
|
6
|
+
|
|
7
|
+
See [what this adds](#loading-bundles-from-esmrun) below; the rest of this README is importmap-rails' own, which this gem tracks at the version in `Importmap::UPSTREAM_VERSION`.
|
|
8
|
+
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
[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.
|
|
12
|
+
|
|
13
|
+
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.
|
|
14
|
+
|
|
15
|
+
[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).
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
## Installation
|
|
19
|
+
|
|
20
|
+
Rails 7+ ships importmap-rails for new applications. To use importmap-plus instead:
|
|
21
|
+
|
|
22
|
+
1. Replace `gem "importmap-rails"` with `gem "importmap-plus"` in your `Gemfile`, or run `./bin/bundle add importmap-plus` in an app that has neither
|
|
23
|
+
2. Run `./bin/rails importmap:install` if the app has no `config/importmap.rb` yet
|
|
24
|
+
|
|
25
|
+
An app already on importmap-rails needs nothing else: the pins, the `config/importmap.rb`, the helpers and the `Importmap::` constants are unchanged.
|
|
26
|
+
|
|
27
|
+
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.
|
|
28
|
+
|
|
29
|
+
You can pin those libraries manually by relying on the compiled versions included in Rails like this:
|
|
30
|
+
|
|
31
|
+
```ruby
|
|
32
|
+
pin "@rails/actioncable", to: "actioncable.esm.js"
|
|
33
|
+
pin "@rails/activestorage", to: "activestorage.esm.js"
|
|
34
|
+
pin "@rails/actiontext", to: "actiontext.esm.js"
|
|
35
|
+
pin "trix"
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
## How do importmaps work?
|
|
39
|
+
|
|
40
|
+
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:
|
|
41
|
+
|
|
42
|
+
- Absolute path:
|
|
43
|
+
```js
|
|
44
|
+
import React from "/Users/DHH/projects/basecamp/node_modules/react"
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
- Relative path:
|
|
48
|
+
```js
|
|
49
|
+
import React from "./node_modules/react"
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
- HTTP path:
|
|
53
|
+
```js
|
|
54
|
+
import React from "https://ga.jspm.io/npm:react@17.0.1/index.js"
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
Importmap-rails provides a clean API for mapping "bare module specifiers" like `"react"`
|
|
58
|
+
to 1 of the 3 viable ways of loading ES Module javascript packages.
|
|
59
|
+
|
|
60
|
+
For example:
|
|
61
|
+
|
|
62
|
+
```rb
|
|
63
|
+
# config/importmap.rb
|
|
64
|
+
pin "react", to: "https://ga.jspm.io/npm:react@17.0.2/index.js"
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
means "every time you see `import React from "react"`
|
|
68
|
+
change it to `import React from "https://ga.jspm.io/npm:react@17.0.2/index.js"`"
|
|
69
|
+
|
|
70
|
+
```js
|
|
71
|
+
import React from "react"
|
|
72
|
+
// => import React from "https://ga.jspm.io/npm:react@17.0.2/index.js"
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
## Usage
|
|
76
|
+
|
|
77
|
+
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.
|
|
78
|
+
|
|
79
|
+
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`.
|
|
80
|
+
|
|
81
|
+
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.
|
|
82
|
+
|
|
83
|
+
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.
|
|
84
|
+
|
|
85
|
+
### Local modules
|
|
86
|
+
|
|
87
|
+
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.
|
|
88
|
+
|
|
89
|
+
```rb
|
|
90
|
+
# config/importmap.rb
|
|
91
|
+
pin_all_from 'app/javascript/src', under: 'src', to: 'src'
|
|
92
|
+
|
|
93
|
+
# With automatic integrity calculation for enhanced security
|
|
94
|
+
enable_integrity!
|
|
95
|
+
pin_all_from 'app/javascript/controllers', under: 'controllers', integrity: true
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
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.
|
|
99
|
+
|
|
100
|
+
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.
|
|
101
|
+
|
|
102
|
+
Allows you to:
|
|
103
|
+
|
|
104
|
+
```js
|
|
105
|
+
// app/javascript/application.js
|
|
106
|
+
import { ExampleFunction } from 'src/example_function'
|
|
107
|
+
```
|
|
108
|
+
Which imports the function from `app/javascript/src/example_function.js`.
|
|
109
|
+
|
|
110
|
+
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.
|
|
111
|
+
|
|
112
|
+
## Using npm packages via JavaScript CDNs
|
|
113
|
+
|
|
114
|
+
Importmap for Rails downloads and vendors your npm package dependencies via JavaScript CDNs that provide pre-compiled distribution versions.
|
|
115
|
+
|
|
116
|
+
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.
|
|
117
|
+
|
|
118
|
+
```bash
|
|
119
|
+
./bin/importmap pin react
|
|
120
|
+
Pinning "react" to vendor/javascript/react.js via download from https://ga.jspm.io/npm:react@19.1.0/index.js
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
This will produce a pin in your `config/importmap.rb` like so:
|
|
124
|
+
|
|
125
|
+
```ruby
|
|
126
|
+
pin "react" # @19.1.0
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
Other CDNs like [unpkg.com](https://unpkg.com) and [jsdelivr.com](https://www.jsdelivr.com) can be specified with `--from`:
|
|
130
|
+
|
|
131
|
+
```bash
|
|
132
|
+
./bin/importmap pin react --from unpkg
|
|
133
|
+
Pinning "react" to vendor/javascript/react.js via download from https://unpkg.com/react@19.1.0/index.js
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
```bash
|
|
137
|
+
./bin/importmap pin react --from jsdelivr
|
|
138
|
+
Pinning "react" to vendor/javascript/react.js via download from https://cdn.jsdelivr.net/npm/react@19.1.0/index.js
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
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.
|
|
142
|
+
|
|
143
|
+
If you later wish to remove a downloaded pin:
|
|
144
|
+
|
|
145
|
+
```bash
|
|
146
|
+
./bin/importmap unpin react
|
|
147
|
+
Unpinning and removing "react"
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
### Pinning to remote CDN URLs
|
|
151
|
+
|
|
152
|
+
If you'd rather load a package straight from the CDN instead of vendoring a download, pass `--remote`:
|
|
153
|
+
|
|
154
|
+
```bash
|
|
155
|
+
./bin/importmap pin react --remote
|
|
156
|
+
Pinning "react" to https://ga.jspm.io/npm:react@19.1.0/index.js
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
This will produce a pin in your `config/importmap.rb` like so:
|
|
160
|
+
|
|
161
|
+
```ruby
|
|
162
|
+
pin "react", to: "https://ga.jspm.io/npm:react@19.1.0/index.js"
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
Remote pins are respected from then on — no `--remote` flag needed. When a remote-pinned package is pinned again or picked up by `./bin/importmap update` (whether directly or as a dependency of another package), the pin stays remote: the URL is re-resolved from the same CDN provider it already points to (`ga.jspm.io`, `unpkg.com`, `cdn.jsdelivr.net`, `cdn.skypack.dev`, or `esm.sh`) instead of being replaced with a download. Pins pointing at any other host are left completely untouched and reported as skipped, and `./bin/importmap pristine` skips remote pins since there is nothing to redownload.
|
|
166
|
+
|
|
167
|
+
Options on existing pins, like `preload: false`, are preserved when a pin is rewritten. An explicit `integrity:` value is dropped when the URL changes, since the old hash would no longer match — see the SRI section below for pinning fresh integrity hashes.
|
|
168
|
+
|
|
169
|
+
### Loading bundles from esm.run
|
|
170
|
+
|
|
171
|
+
[esm.run](https://www.jsdelivr.com/esm) is jsDelivr's bundling endpoint: it serves one minified ES module per package, no matter what the package ships on npm. Where jspm hands you a package's own `dist` file (unminified for plenty of packages), `--from esm.run` gives you the bundle:
|
|
172
|
+
|
|
173
|
+
```bash
|
|
174
|
+
./bin/importmap pin luxon --from esm.run
|
|
175
|
+
Pinning "luxon" to vendor/javascript/luxon.js via download from https://cdn.jsdelivr.net/npm/luxon@3.7.2/+esm
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
A bundle references the packages it depends on as absolute `/npm/dep@1.2.3/+esm` imports, which only resolve on jsDelivr. When the bundle is vendored, those imports are rewritten to bare specifiers (`import { Controller } from "@hotwired/stimulus"`) so they resolve through your import map, and every dependency without a pin is pinned the same way — vendored from esm.run, at the version the bundle was built against:
|
|
179
|
+
|
|
180
|
+
```bash
|
|
181
|
+
./bin/importmap pin stimulus-use --from esm.run
|
|
182
|
+
Pinning "stimulus-use" to vendor/javascript/stimulus-use.js via download from https://cdn.jsdelivr.net/npm/stimulus-use@0.53.1/+esm
|
|
183
|
+
Keeping existing pin for "@hotwired/stimulus" (bundle was built against @3.2.2)
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
A dependency you already pin is left alone: the bundle then resolves to whatever your import map says, exactly like a jspm download would. With `--remote`, the pin points at the bundle URL and its imports load from jsDelivr as-is.
|
|
187
|
+
|
|
188
|
+
Versions are resolved through jsDelivr's data API, so `pin luxon@3 --from esm.run` and subpaths like `pin apexcharts/core --from esm.run` work the way they do on npm.
|
|
189
|
+
|
|
190
|
+
### Where a package came from is remembered
|
|
191
|
+
|
|
192
|
+
The version comment on a vendored pin also names the CDN when it isn't jspm:
|
|
193
|
+
|
|
194
|
+
```ruby
|
|
195
|
+
pin "luxon" # @3.7.2 (esm.run)
|
|
196
|
+
pin "react" # @19.1.0 (unpkg)
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
`./bin/importmap update` and `./bin/importmap pristine` read it and go back to the same CDN — an esm.run bundle stays a bundle, an unpkg download stays on unpkg — and so does `pin` when you leave out `--from`. Pass `--from` to move a package to another CDN; an explicit `--from` moves a remote pin too, which is otherwise re-resolved from the CDN it already points at.
|
|
200
|
+
|
|
201
|
+
### Minifying vendored packages
|
|
202
|
+
|
|
203
|
+
Lighthouse's unminified-javascript audit will tell you which packages ship unminified builds. Pass `--minify` to run a download through a JavaScript minifier before it lands in `vendor/javascript`:
|
|
204
|
+
|
|
205
|
+
```bash
|
|
206
|
+
./bin/importmap pin luxon --minify
|
|
207
|
+
Pinning "luxon" to vendor/javascript/luxon.js via download from https://ga.jspm.io/npm:luxon@3.7.2/build/es6/luxon.mjs (minified)
|
|
208
|
+
```
|
|
209
|
+
|
|
210
|
+
The first of [bun](https://bun.sh), [esbuild](https://esbuild.github.io) or [terser](https://terser.org) found in `node_modules/.bin` or on your `PATH` is used, always in transform-only mode so bare import specifiers are left exactly as the CDN resolved them. The pin records it (`pin "luxon" # @3.7.2 (minified)`, or `(esm.run, minified)` for a bundle), and from then on `update`, `pristine` and a plain `pin` keep minifying that package; `--no-minify` turns it off again, and `./bin/importmap pristine --minify` minifies everything you have vendored in one go.
|
|
211
|
+
|
|
212
|
+
To use a different minifier, assign anything that responds to `call(source)` and returns the minified source. `bin/importmap` loads `config/application.rb` but not your initializers, so the assignment has to happen there (or in a file it requires):
|
|
213
|
+
|
|
214
|
+
```ruby
|
|
215
|
+
# config/application.rb
|
|
216
|
+
require "importmap/packager"
|
|
217
|
+
|
|
218
|
+
Importmap::Packager.minifier = ->(source) { MyMinifier.minify(source) }
|
|
219
|
+
```
|
|
220
|
+
|
|
221
|
+
## Subresource Integrity (SRI)
|
|
222
|
+
|
|
223
|
+
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.
|
|
224
|
+
|
|
225
|
+
### Automatic integrity for local assets
|
|
226
|
+
|
|
227
|
+
To enable automatic integrity calculation for local assets served by the Rails asset pipeline, you must first call `enable_integrity!` in your importmap configuration:
|
|
228
|
+
|
|
229
|
+
```ruby
|
|
230
|
+
# config/importmap.rb
|
|
231
|
+
|
|
232
|
+
# Enable integrity calculation globally
|
|
233
|
+
enable_integrity!
|
|
234
|
+
|
|
235
|
+
# With integrity enabled, these will auto-calculate integrity hashes
|
|
236
|
+
pin "application" # Auto-calculated integrity
|
|
237
|
+
pin "admin", to: "admin.js" # Auto-calculated integrity
|
|
238
|
+
pin_all_from "app/javascript/controllers", under: "controllers" # Auto-calculated integrity
|
|
239
|
+
|
|
240
|
+
# Mixed usage - explicitly controlling integrity
|
|
241
|
+
pin "cdn_package", integrity: "sha384-abc123..." # Pre-calculated hash
|
|
242
|
+
pin "no_integrity_package", integrity: false # Explicitly disable integrity
|
|
243
|
+
pin "nil_integrity_package", integrity: nil # Explicitly disable integrity
|
|
244
|
+
```
|
|
245
|
+
|
|
246
|
+
This is particularly useful for:
|
|
247
|
+
* **Local JavaScript files** managed by your Rails asset pipeline
|
|
248
|
+
* **Bulk operations** with `pin_all_from` where calculating hashes manually would be tedious
|
|
249
|
+
* **Development workflow** where asset contents change frequently
|
|
250
|
+
|
|
251
|
+
**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.
|
|
252
|
+
|
|
253
|
+
**Important for Propshaft users:** SRI support requires Propshaft 1.2+ and you must configure the integrity hash algorithm in your application:
|
|
254
|
+
|
|
255
|
+
```ruby
|
|
256
|
+
# config/application.rb or config/environments/*.rb
|
|
257
|
+
config.assets.integrity_hash_algorithm = 'sha256' # or 'sha384', 'sha512'
|
|
258
|
+
```
|
|
259
|
+
|
|
260
|
+
Without this configuration, integrity will be disabled by default when using Propshaft. Sprockets includes integrity support out of the box.
|
|
261
|
+
|
|
262
|
+
**Example output with `enable_integrity!` and `integrity: true`:**
|
|
263
|
+
```json
|
|
264
|
+
{
|
|
265
|
+
"imports": {
|
|
266
|
+
"application": "/assets/application-abc123.js",
|
|
267
|
+
"controllers/hello_controller": "/assets/controllers/hello_controller-def456.js"
|
|
268
|
+
},
|
|
269
|
+
"integrity": {
|
|
270
|
+
"/assets/application-abc123.js": "sha256-xyz789...",
|
|
271
|
+
"/assets/controllers/hello_controller-def456.js": "sha256-uvw012..."
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
```
|
|
275
|
+
|
|
276
|
+
### How integrity works
|
|
277
|
+
|
|
278
|
+
The integrity hashes are automatically included in your import map and module preload tags:
|
|
279
|
+
|
|
280
|
+
**Import map JSON:**
|
|
281
|
+
```json
|
|
282
|
+
{
|
|
283
|
+
"imports": {
|
|
284
|
+
"lodash": "https://ga.jspm.io/npm:lodash@4.17.21/lodash.js",
|
|
285
|
+
"application": "/assets/application-abc123.js",
|
|
286
|
+
"controllers/hello_controller": "/assets/controllers/hello_controller-def456.js"
|
|
287
|
+
},
|
|
288
|
+
"integrity": {
|
|
289
|
+
"https://ga.jspm.io/npm:lodash@4.17.21/lodash.js": "sha384-PkIkha4kVPRlGtFantHjuv+Y9mRefUHpLFQbgOYUjzy247kvi16kLR7wWnsAmqZF"
|
|
290
|
+
"/assets/application-abc123.js": "sha256-xyz789...",
|
|
291
|
+
"/assets/controllers/hello_controller-def456.js": "sha256-uvw012..."
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
```
|
|
295
|
+
|
|
296
|
+
**Module preload tags:**
|
|
297
|
+
```html
|
|
298
|
+
<link rel="modulepreload" href="https://ga.jspm.io/npm:lodash@4.17.21/lodash.js" integrity="sha384-PkIkha4kVPRlGtFantHjuv+Y9mRefUHpLFQbgOYUjzy247kvi16kLR7wWnsAmqZF">
|
|
299
|
+
<link rel="modulepreload" href="/assets/application-abc123.js" integrity="sha256-xyz789...">
|
|
300
|
+
<link rel="modulepreload" href="/assets/controllers/hello_controller-def456.js" integrity="sha256-uvw012...">
|
|
301
|
+
```
|
|
302
|
+
|
|
303
|
+
Modern browsers will automatically validate these integrity hashes when loading the JavaScript modules, ensuring the files haven't been modified.
|
|
304
|
+
|
|
305
|
+
## Preloading pinned modules
|
|
306
|
+
|
|
307
|
+
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.
|
|
308
|
+
|
|
309
|
+
Example:
|
|
310
|
+
|
|
311
|
+
```ruby
|
|
312
|
+
# config/importmap.rb
|
|
313
|
+
pin "@github/hotkey", to: "@github--hotkey.js" # file lives in vendor/javascript/@github--hotkey.js
|
|
314
|
+
pin "md5", preload: false # file lives in vendor/javascript/md5.js
|
|
315
|
+
|
|
316
|
+
# app/views/layouts/application.html.erb
|
|
317
|
+
<%= javascript_importmap_tags %>
|
|
318
|
+
|
|
319
|
+
# will include the following link before the importmap is setup:
|
|
320
|
+
<link rel="modulepreload" href="/assets/javascript/@github--hotkey.js">
|
|
321
|
+
...
|
|
322
|
+
```
|
|
323
|
+
|
|
324
|
+
You can also specify which entry points to preload a particular dependency in by providing `preload:` a string or array of strings.
|
|
325
|
+
|
|
326
|
+
Example:
|
|
327
|
+
|
|
328
|
+
```ruby
|
|
329
|
+
# config/importmap.rb
|
|
330
|
+
pin "@github/hotkey", to: "@github--hotkey.js", preload: 'application'
|
|
331
|
+
pin "md5", preload: ['application', 'alternate']
|
|
332
|
+
|
|
333
|
+
# app/views/layouts/application.html.erb
|
|
334
|
+
<%= javascript_importmap_tags 'alternate' %>
|
|
335
|
+
|
|
336
|
+
# will include the following link before the importmap is setup:
|
|
337
|
+
<link rel="modulepreload" href="/assets/javascript/md5.js">
|
|
338
|
+
...
|
|
339
|
+
```
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
## Composing import maps
|
|
344
|
+
|
|
345
|
+
By default, Rails loads import map definition from the application's `config/importmap.rb` to the `Importmap::Map` object available at `Rails.application.importmap`.
|
|
346
|
+
|
|
347
|
+
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:
|
|
348
|
+
|
|
349
|
+
```ruby
|
|
350
|
+
# my_engine/lib/my_engine/engine.rb
|
|
351
|
+
|
|
352
|
+
module MyEngine
|
|
353
|
+
class Engine < ::Rails::Engine
|
|
354
|
+
# ...
|
|
355
|
+
initializer "my-engine.importmap", before: "importmap" do |app|
|
|
356
|
+
app.config.importmap.paths << Engine.root.join("config/importmap.rb")
|
|
357
|
+
# ...
|
|
358
|
+
end
|
|
359
|
+
end
|
|
360
|
+
end
|
|
361
|
+
```
|
|
362
|
+
|
|
363
|
+
And pinning JavaScript modules from the engine:
|
|
364
|
+
|
|
365
|
+
```ruby
|
|
366
|
+
# my_engine/config/importmap.rb
|
|
367
|
+
|
|
368
|
+
pin_all_from File.expand_path("../app/assets/javascripts", __dir__)
|
|
369
|
+
```
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
## Selectively importing modules
|
|
373
|
+
|
|
374
|
+
You can selectively import your javascript modules on specific pages.
|
|
375
|
+
|
|
376
|
+
Create your javascript in `app/javascript`:
|
|
377
|
+
|
|
378
|
+
```js
|
|
379
|
+
// /app/javascript/checkout.js
|
|
380
|
+
// some checkout specific js
|
|
381
|
+
```
|
|
382
|
+
|
|
383
|
+
Pin your js file:
|
|
384
|
+
|
|
385
|
+
```rb
|
|
386
|
+
# config/importmap.rb
|
|
387
|
+
# ... other pins...
|
|
388
|
+
pin "checkout", preload: false
|
|
389
|
+
```
|
|
390
|
+
|
|
391
|
+
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.
|
|
392
|
+
|
|
393
|
+
```erb
|
|
394
|
+
<% content_for :head do %>
|
|
395
|
+
<%= javascript_import_module_tag "checkout" %>
|
|
396
|
+
<% end %>
|
|
397
|
+
```
|
|
398
|
+
|
|
399
|
+
**Important**: The `javascript_import_module_tag` should come after your `javascript_importmap_tags`
|
|
400
|
+
|
|
401
|
+
```erb
|
|
402
|
+
<%= javascript_importmap_tags %>
|
|
403
|
+
<%= yield(:head) %>
|
|
404
|
+
```
|
|
405
|
+
|
|
406
|
+
|
|
407
|
+
## Include a digest of the import map in your ETag
|
|
408
|
+
|
|
409
|
+
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:
|
|
410
|
+
|
|
411
|
+
```ruby
|
|
412
|
+
class ApplicationController < ActionController::Base
|
|
413
|
+
stale_when_importmap_changes
|
|
414
|
+
end
|
|
415
|
+
```
|
|
416
|
+
|
|
417
|
+
This will add the digest of the importmap to the etag calculation when the request format is HTML.
|
|
418
|
+
|
|
419
|
+
|
|
420
|
+
## Sweeping the cache in development and test
|
|
421
|
+
|
|
422
|
+
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`.
|
|
423
|
+
|
|
424
|
+
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:
|
|
425
|
+
|
|
426
|
+
```ruby
|
|
427
|
+
# my_engine/lib/my_engine/engine.rb
|
|
428
|
+
|
|
429
|
+
module MyEngine
|
|
430
|
+
class Engine < ::Rails::Engine
|
|
431
|
+
# ...
|
|
432
|
+
initializer "my-engine.importmap", before: "importmap" do |app|
|
|
433
|
+
# ...
|
|
434
|
+
app.config.importmap.cache_sweepers << Engine.root.join("app/assets/javascripts")
|
|
435
|
+
end
|
|
436
|
+
end
|
|
437
|
+
end
|
|
438
|
+
```
|
|
439
|
+
|
|
440
|
+
## Checking for outdated or vulnerable packages
|
|
441
|
+
|
|
442
|
+
Importmap for Rails provides two commands to check your pinned packages:
|
|
443
|
+
- `./bin/importmap outdated` checks the NPM registry for new versions
|
|
444
|
+
- `./bin/importmap audit` checks the NPM registry for known security issues
|
|
445
|
+
|
|
446
|
+
## Supporting legacy browsers such as Safari on iOS 15
|
|
447
|
+
|
|
448
|
+
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.
|
|
449
|
+
|
|
450
|
+
```erb
|
|
451
|
+
<script async src="https://ga.jspm.io/npm:es-module-shims@1.8.2/dist/es-module-shims.js" data-turbo-track="reload"></script>
|
|
452
|
+
<%= javascript_importmap_tags %>
|
|
453
|
+
```
|
|
454
|
+
|
|
455
|
+
## License
|
|
456
|
+
|
|
457
|
+
Importmap for Rails is released under the [MIT License](https://opensource.org/licenses/MIT).
|
data/Rakefile
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
require "bundler/setup"
|
|
2
|
+
|
|
3
|
+
APP_RAKEFILE = File.expand_path("test/dummy/Rakefile", __dir__)
|
|
4
|
+
load "rails/tasks/engine.rake"
|
|
5
|
+
|
|
6
|
+
require "bundler/gem_tasks"
|
|
7
|
+
|
|
8
|
+
require "rake/testtask"
|
|
9
|
+
|
|
10
|
+
Rake::TestTask.new(:test) do |t|
|
|
11
|
+
t.libs << 'test'
|
|
12
|
+
t.pattern = 'test/**/*_test.rb'
|
|
13
|
+
t.verbose = false
|
|
14
|
+
t.warning = false
|
|
15
|
+
end
|
|
16
|
+
|
|
17
|
+
task default: :test
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
module Importmap::ImportmapTagsHelper
|
|
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", importmap: Rails.application.importmap)
|
|
4
|
+
safe_join [
|
|
5
|
+
javascript_inline_importmap_tag(importmap.to_json(resolver: self)),
|
|
6
|
+
javascript_importmap_module_preload_tags(importmap, entry_point:),
|
|
7
|
+
javascript_import_module_tag(entry_point)
|
|
8
|
+
], "\n"
|
|
9
|
+
end
|
|
10
|
+
|
|
11
|
+
# Generate an inline importmap tag using the passed `importmap_json` JSON string.
|
|
12
|
+
# By default, `Rails.application.importmap.to_json(resolver: self)` is used.
|
|
13
|
+
def javascript_inline_importmap_tag(importmap_json = Rails.application.importmap.to_json(resolver: self))
|
|
14
|
+
tag.script importmap_json.html_safe,
|
|
15
|
+
type: "importmap", "data-turbo-track": "reload", nonce: request&.content_security_policy_nonce
|
|
16
|
+
end
|
|
17
|
+
|
|
18
|
+
# Import a named JavaScript module(s) using a script-module tag.
|
|
19
|
+
def javascript_import_module_tag(*module_names)
|
|
20
|
+
imports = Array(module_names).collect { |m| %(import "#{m}") }.join("\n")
|
|
21
|
+
tag.script imports.html_safe, type: "module", nonce: request&.content_security_policy_nonce
|
|
22
|
+
end
|
|
23
|
+
|
|
24
|
+
# Link tags for preloading all modules marked as preload: true in the `importmap`
|
|
25
|
+
# (defaults to Rails.application.importmap), such that they'll be fetched
|
|
26
|
+
# in advance by browsers supporting this link type (https://caniuse.com/?search=modulepreload).
|
|
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 }] }
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
# Link tag(s) for preloading the JavaScript module residing in `*paths`. Will return one link tag per path element.
|
|
34
|
+
def javascript_module_preload_tag(*paths)
|
|
35
|
+
_generate_preload_tags(paths) { |path| [path, {}] }
|
|
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
|
|
47
|
+
end
|