Import maps for Rails, built by jspm.
Your JavaScript ships as the ES modules its authors wrote. There's no bundler, no build step and no Node in production, and the browser caches each module on its own. Use jspm alone, or install packages with npm too. npm then sets their versions, so Dependabot keeps working.
bin/rails jspm:install traced ./app/javascript/application.js
vendored 31 modules from ga.jspm.io
wrote config/importmap.json
Contents
- Why
- Quick start
- Writing your JavaScript
- Versions: plain jspm, or npm too
- Stylesheets, fonts and images
- Keeping up to date
- Warnings
- Deploying
- How it works
- Compared to
- FAQ
- Troubleshooting
- Development
Why
Rails 8 ships import maps by default, through importmap-rails. It vendors one file per package. That works until a package imports its own internal files or depends on other packages. Then you pin the whole tree by hand, and bin/importmap update can't tell which versions belong together. A package spread across many modules ends up split across versions, or missing files.
jspm solves that. It traces your code and finds every module your code reaches, across whole dependency trees. jspm-rails runs that trace, vendors what it finds, and hands the result to Propshaft. So you get import maps that work for any package on npm, with versions locked the way you'd expect.
Quick start
You need Rails 8 with Propshaft, and Node with npm on your development machine.
bundle add jspm-rails
npm install --save-dev @jspm/generatorRender the tags in your layout's <head>:
<%= javascript_jspm_tags %>Write app/javascript/application.js:
import confetti from 'canvas-confetti'
confetti()Install, and commit what it writes:
bin/rails jspm:install
git add config/importmap.json vendor/jspmTo have GitHub collapse those generated files in pull requests, mark them in .gitattributes:
config/importmap.json linguist-generated
vendor/jspm/** linguist-generated
Reload the page.
Writing your JavaScript
The entry point is app/javascript/application.js. javascript_jspm_tags loads it as a module, and the install traces everything it imports. For a layout that needs a different entry, see the FAQ.
Import packages by name, as their documentation shows:
import TomSelect from 'tom-select'
import { Controller } from '@hotwired/stimulus'Import your own modules by asset name, as importmap-rails pins them: the logical path without its extension, and a directory's name for its index.js. Relative paths work too:
import { setUpForms } from 'forms' // app/javascript/forms.js
import 'controllers' // app/javascript/controllers/index.js
import { helper } from './helpers.js'Every module in app/javascript is in the import map by name, even ones nothing imports directly, as importmap-rails's pin_all_from names them. So stimulus-rails's eagerLoadControllersFrom("controllers", application) and lazyLoadControllersFrom work unchanged.
Import modules that gems ship the same way. Every engine's app/assets directories are on Propshaft's load path, so a gem's modules are importable by asset name with no setup:
import MathController from 'astrology/math_controller'Import rarely used code dynamically. The install vendors it too, but the page doesn't preload it, so the browser fetches it only when it runs:
const { default: katex } = await import('katex')Versions: plain jspm, or npm too
Plain jspm works on its own. The install resolves each package you import from jspm.io. That's the latest version, or the newest within a range you give in package.json's dependencies, as jspm does. config/importmap.json is jspm's lockfile: every install keeps the versions it already holds.
Install a package with npm or Yarn 1 when you want more. Its version in package-lock.json or yarn.lock then overrides the import map, and you get:
- Dependabot pull requests for it.
- Its stylesheets, fonts and images in
node_modules, at the same version as its JavaScript.
Mix the two freely. A package's JavaScript always comes from jspm.io either way. npm decides the version, not the files.
Stylesheets, fonts and images
jspm.io serves JavaScript. For a package's other files, install it with npm and put the directory that holds them on Propshaft's load path, as Rails's generated config/initializers/assets.rb suggests:
Rails.application.config.assets.paths << Rails.root.join('node_modules/katex/dist')<%= stylesheet_link_tag 'katex' %>Propshaft rewrites the url()s in the stylesheet to digested paths, so the fonts load too. The CSS comes from npm and the JavaScript from jspm.io, both at the version in your lockfile.
Add the directory you use, not the whole package or all of node_modules. Propshaft checks every file on its load path before each development request and precompiles every one, so bootstrap-icons/font (7 files) costs far less than the package (2,089).
Keeping up to date
npm packages: when Dependabot, or you, changes package-lock.json, run bin/rails jspm:install again.
Plain jspm packages: delete the package's entries from config/importmap.json, then run the install. jspm resolves it afresh.
To keep the map from drifting, run the check in CI:
bin/rails jspm:checkIt traces again without writing anything. It fails when an install would change config/importmap.json, for example after Dependabot bumps package-lock.json. It also downloads every vendored file again and fails when one in vendor/jspm is missing or differs from what jspm.io serves. A hand edit to vendored code can't pass CI, so it's safe to collapse vendor/jspm in diffs:
stale config/importmap.json
run bin/rails jspm:install
Warnings
The install warns when the import map can't match package-lock.json:
warn @orchidjs/unicode-variants: package-lock.json has 1.1.1 and 1.2.2, and the import map uses 1.1.1 everywhere
npm installs two versions of a package when its dependents' ranges don't overlap. An import map gives each package one version per scope, so jspm-rails uses the top-level version everywhere and tells you. Check that the packages needing the other version still work, or upgrade them so the ranges meet.
Deploying
-
Commit
config/importmap.jsonandvendor/jspm.assets:precompiledigests the vendored modules like any other asset. -
Production needs no jspm.io, and no Node unless you serve stylesheets from
node_modules, which needs your packages installed before precompiling. -
An
asset_hoston another origin must sendAccess-Control-Allow-Origin. Browsers load modules and fonts across origins only with CORS. - Content Security Policy works. Every tag carries the request's nonce.
-
Turbo reloads the page when the import map changes, because the map's tag has
data-turbo-track="reload".
How it works
bin/rails jspm:install:
- Boots the app, then traces
app/javascript/application.jswith@jspm/generator. Every module on Propshaft's load path is importable by asset name. The previousconfig/importmap.jsonlocks versions, andpackage-lock.jsonpins every package npm installed. Only packages your code reaches end up in the map, so KaTeX's command-line dependency stays out. - Downloads each traced module from jspm.io, with its source map, into
vendor/jspm/ga.jspm.io. - Writes jspm's import map to
config/importmap.json, with the list of modules to preload. Local modules appear asasset:plus their logical path, such asasset:astrology/math_controller.js, so the map is the same on every machine.
javascript_jspm_tags renders that map for Propshaft. Propshaft serves each file under a digested name, so the helper rewrites the map's URLs:
"tom-select": "https://ga.jspm.io/npm:tom-select@2.4.3/dist/esm/tom-select.complete.js"becomes
"tom-select": "/assets/ga.jspm.io/npm/tom-select@2.4.3/dist/esm/tom-select.complete-c479c3ee.js"A module imports its siblings by their plain names, though. When tom-select.complete.js imports ./constants.js, the browser asks for /assets/.../constants.js, which Propshaft doesn't serve. So the rendered map also sends each plain module URL to its digested one:
"/assets/ga.jspm.io/npm/tom-select@2.4.3/dist/esm/constants.js":
"/assets/ga.jspm.io/npm/tom-select@2.4.3/dist/esm/constants-115aef3a.js"That's a standard import-map feature, so nothing gets rewritten inside the files.
Compared to
- importmap-rails pins one file per package, and you resolve the dependency tree by hand. jspm-rails traces the whole tree.
- jsbundling-rails resolves the tree too, but compiles your JavaScript into a bundle. That means a watcher in development and a build in CI and deploys. And a change to any module busts the cache for the whole bundle. jspm-rails ships the modules as written.
FAQ
Why vendor, instead of loading from jspm.io? For the reasons importmap-rails switched to vendoring in rails/importmap-rails#217. Under HTTP/2, every extra origin costs a connection, so serving from your own costs less. Your app also stops depending on a third party at runtime, and development works offline.
Do I need npm at all?
You need it to install @jspm/generator. Beyond that, no: plain jspm packages need nothing in package.json.
Can I use TypeScript or JSX? Not with jspm-rails, which doesn't transpile. Use jsbundling-rails.
Can I import a stylesheet as a module (with { type: 'css' })?
Safari doesn't support CSS module scripts yet, so link stylesheets with stylesheet_link_tag.
Can I have more than one entry point?
Yes. A layout whose pages need different code loads app/javascript/admin.js with javascript_jspm_entry_tags('admin'). The install traces every module in app/javascript, so any of them can be an entry.
Can I use it alongside importmap-rails? Use one or the other. Both render the page's import map.
Does it work on Windows? It's untested there.
Troubleshooting
tracing ./app/javascript/application.js failed
Node printed the reason just above. Usually Node isn't on your PATH, or @jspm/generator isn't installed: run npm install --save-dev @jspm/generator.
Propshaft::MissingAssetError for a file under ga.jspm.io
config/importmap.json names a module that vendor/jspm doesn't have. Run bin/rails jspm:install and commit both.
Modules or fonts fail to load with an asset host
The asset host must send Access-Control-Allow-Origin. See Deploying.
A package's stylesheet raises Propshaft::MissingAssetError
Add its directory to config.assets.paths. See Stylesheets, fonts and images.
Development
bundle install
npm ci && npx playwright install chromium
(cd spec/dummy && npm ci) && (cd spec/fixtures/conflicted && npm ci) && (cd spec/fixtures/yarn && yarn install --frozen-lockfile)
bundle exec rakeThe specs install into a dummy Rails app through bin/rails jspm:install. Then they drive it in Chromium through Playwright, on one origin and on two, finding elements by their accessible role and name. Any JavaScript error fails the example. So they need network access to jspm.io.
Report security issues privately; see SECURITY.md.