skip to content

In a Rails 8.1 app on importmap-rails, how do config/importmap.rb and javascript_importmap_tags let the browser run import statements with no Node build step?

level: juniorimportance: must knowfreq 58%

answer

  1. bare name mapped to a digested URL
  2. pin name, to: logical path
  3. app/javascript and vendor/javascript on the load path
  4. importmap JSON, modulepreload, import application
  5. local modules need a pin under Propshaft

basics

~20 s

config/importmap.rb pins bare module names to files on the asset load path; javascript_importmap_tags renders those pins as a script type="importmap" block of digested URLs, adds modulepreload links and imports "application", so the browser resolves every import natively.

solid answer

~40 s

Browsers resolve a bare specifier such as `"@hotwired/turbo-rails"` only through an import map. importmap-rails builds one from `config/importmap.rb`: each `pin "name", to: "file.js"` maps a name to a logical asset path, and `pin_all_from` does that for a whole folder. The gem adds `app/javascript` and `vendor/javascript` to `config.assets.paths`, so Propshaft finds the files and `path_to_asset` turns each into a digested `/assets/...` URL. `javascript_importmap_tags` in the layout then renders three things: the inline `<script type="importmap">` JSON, `<link rel="modulepreload">` tags for preloaded pins, and `<script type="module">import "application"</script>`. Nothing is transpiled or bundled; the browser fetches each module as its own file. Under Propshaft every local module you import must be pinned.

code

html · 10 lines
html
<script type="importmap" data-turbo-track="reload">{
  "imports": {
    "application": "/assets/application-3f9a1c2e.js",
    "@hotwired/turbo-rails": "/assets/turbo.min-8b1d0e44.js",
    "controllers/hello_controller": "/assets/controllers/hello_controller-0c7d5a91.js"
  }
}</script>
<link rel="modulepreload" href="/assets/application-3f9a1c2e.js">
<link rel="modulepreload" href="/assets/turbo.min-8b1d0e44.js">
<script type="module">import "application"</script>

go deeper

for a junior

Recall the chain: pin in config/importmap.rb, javascript_importmap_tags in the layout, the browser resolving import names through the JSON map.

for a middle

Explain how pins become digested URLs through Propshaft's load path, the three tags the helper renders, and why local modules must be pinned.

for a senior

Diagnose missing modules: skipped-path warnings, bin/importmap json, removed pins lingering until restart, and stale HTML caches without stale_when_importmap_changes.

for a principal

Explain the bet import maps make: HTTP/2 and per-file caching instead of a build pipeline, and what the team gives up in exchange.

## The problem import maps solve In JavaScript modules, `import { Turbo } from "@hotwired/turbo-rails"` uses a **bare specifier** — a name rather than a path or URL. A browser cannot fetch a bare name on its own; something has to say which URL it means. Bundlers answer that at build time. An **import map**, a JSON block the page declares, answers it in the browser. **importmap-rails** is the gem that writes that JSON from Ruby, so a Rails app can ship ES modules with no Node, no `package.json` and no build step. A Rails 8.1 `rails new` uses it by default (`--javascript` defaults to `importmap`). ## config/importmap.rb The file is Ruby evaluated by `Importmap::Map#draw`. A new Rails 8.1 app ends up with: ```ruby pin "application" pin "@hotwired/turbo-rails", to: "turbo.min.js" pin "@hotwired/stimulus", to: "stimulus.min.js" pin "@hotwired/stimulus-loading", to: "stimulus-loading.js" pin_all_from "app/javascript/controllers", under: "controllers" ``` - `pin "application"` maps the name `application` to the logical path `application.js` (the default `to:` is `"#{name}.js"`), which is `app/javascript/application.js`. - `to:` names any logical path on the asset load path. `turbo.min.js` comes from the turbo-rails gem's own assets, not from your repository. - `pin_all_from` walks a folder and pins every `.js` file, naming each module after its path under `under:` — `controllers/hello_controller` for `app/javascript/controllers/hello_controller.js`. ## How a pin becomes a URL 1. The importmap-rails engine appends `app/javascript` and `vendor/javascript` to `config.assets.paths`, so **Propshaft** can find pinned files. 2. When the map is rendered, each pin's path goes through the view's `path_to_asset`, which Propshaft resolves to a digested URL such as `/assets/application-3f9a1c2e.js`. 3. `to:` may also be a full `https://` URL; `path_to_asset` returns it unchanged. That is how older tutorials pinned CDN files; `bin/importmap pin` now downloads files into `vendor/javascript` instead. 4. If Propshaft cannot find a pinned file, importmap-rails rescues `Propshaft::MissingAssetError`, logs `Importmap skipped missing path`, and leaves that pin out of the map. ## What javascript_importmap_tags renders `javascript_importmap_tags(entry_point = "application")` emits, in this order: | Output | Purpose | |---|---| | `<script type="importmap">` with the JSON map | tells the browser which URL each bare name means | | `<link rel="modulepreload">` per preloaded pin | starts downloads early instead of discovering imports one level at a time | | `<script type="module">import "application"</script>` | loads the entry point, which imports the rest | Each tag carries the request's CSP nonce when one is configured, and the map tag has `data-turbo-track="reload"`. The helper is a combination of three public ones: `javascript_inline_importmap_tag`, `javascript_importmap_module_preload_tags` and `javascript_import_module_tag`. ## The rule that surprises people Under Propshaft, **every local module you import needs a pin**. If you add `app/javascript/campsites/availability.js` and write `import "campsites/availability"`, the browser looks the name up in the map, finds nothing and throws a resolution error. Sprockets used to serve unpinned files from `app/javascript` by relative path; Propshaft has no such fallback. The fix is a `pin` or a `pin_all_from "app/javascript/campsites", under: "campsites"`. ## Development behaviour - `config/importmap.rb` is reloaded on change, but the README warns that **removed** pins can linger in the rendered map and preloads until the server restarts. - The rendered JSON and preload list are cached; in development and test (`config.importmap.sweep_cache`) changes under `app/javascript` and `vendor/javascript` clear that cache. - `bin/importmap json` prints the fully resolved map, which is the quickest way to see what the browser will receive. ## What it does not do There is no transpiling, so no TypeScript or JSX, and no bundling or tree-shaking: each module is its own HTTP request, which HTTP/2 makes affordable and which lets a change to one file invalidate only that file's cache entry. ## One page load, traced Following a single request through a fresh Rails 8.1 app makes the pieces concrete: 1. The layout renders `javascript_importmap_tags`, so the HTML carries the map, a modulepreload link for every preloaded pin, and `import "application"`. 2. The browser starts fetching the preloaded files at once, in parallel, while it parses the rest of the page. 3. The module script imports `application`; the map turns that into `/assets/application-<digest>.js`. 4. `application.js` contains `import "@hotwired/turbo-rails"` and `import "controllers"`. Each name is looked up in the same map, and because the files were preloaded they are usually already in memory. 5. The controllers index loads each Stimulus controller by its `controllers/...` name, which `pin_all_from` put in the map. At no point does the server compile anything: every URL in the map points at a file Propshaft copied and digested during `bin/rails assets:precompile`.

  • A pin's to: has a typo, so the file does not exist. What do you see?
    No exception while rendering: importmap-rails rescues `Propshaft::MissingAssetError`, logs `Importmap skipped missing path: ...` and drops that pin from the JSON. The failure appears in the browser instead, as a module-resolution error the moment something imports that name. `bin/importmap json` shows the pin is missing.
  • Why does the generated ApplicationController call stale_when_importmap_changes?
    It adds a SHA1 digest of the rendered import map JSON to the ETag of HTML responses. Without it, a page answered with 304 Not Modified could keep a stale map pointing at old digested JavaScript after a deploy. It is importmap-rails' own controller macro, added when the app uses import maps.

A hotel switchboard card: guests ask for "reception" or "kitchen" by name, and the card on the operator's desk says which extension each name rings today. Move the kitchen to a new extension and only the card changes; ask for a name that is not on the card and the call goes nowhere.

  • importmap-rails bundles app/javascript into one application.js at precompile
  • Pinned packages are fetched from the JSPM CDN on every page load
  • Any file under app/javascript can be imported by name without a pin
  • javascript_importmap_tags needs Node installed on the server to build the map
  • The import map JSON lists undigested paths and Propshaft rewrites them later