• Stars
    star
    1,037
  • Rank 44,422 (Top 0.9 %)
  • Language
    Ruby
  • License
    MIT License
  • Created over 3 years ago
  • Updated 4 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Use ESM with importmap to manage modern JavaScript in Rails without transpiling or bundling.

Importmap for Rails

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. 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.

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.

Import maps are supported natively in all major, modern browsers. If you need to work with legacy browsers without native support, you can explore using the shim available.

Installation

Importmap for Rails is automatically included in Rails 7+ for new applications, but you can also install it manually in existing applications:

  1. Run ./bin/bundle add importmap-rails
  2. Run ./bin/rails importmap:install

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.

You can pin those libraries manually by relying on the compiled versions included in Rails like this:

pin "@rails/actioncable", to: "actioncable.esm.js"
pin "@rails/activestorage", to: "activestorage.esm.js"
pin "@rails/actiontext", to: "actiontext.esm.js"
pin "trix"

How do importmaps work?

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:

  • Absolute path:
import React from "/Users/DHH/projects/basecamp/node_modules/react"
  • Relative path:
import React from "./node_modules/react"
  • HTTP path:
import React from "https://ga.jspm.io/npm:[email protected]/index.js"

Importmap-rails provides a clean API for mapping "bare module specifiers" like "react" to 1 of the 3 viable ways of loading ES Module javascript packages.

For example:

# config/importmap.rb
pin "react", to: "https://ga.jspm.io/npm:[email protected]/index.js"

means "everytime you see import React from "react" change it to import React from "https://ga.jspm.io/npm:[email protected]/index.js""

import React from "react" 
// => import React from "https://ga.jspm.io/npm:[email protected]/index.js"

Usage

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.

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.

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.

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.

Local modules

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.

# config/importmap.rb
pin_all_from 'app/javascript/src', under: 'src', to: 'src'

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.

Allows you to:

// app/javascript/application.js
import { ExampleFunction } from 'src/example_function'

Which imports the function from app/javascript/src/example_function.js.

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.

Using npm packages via JavaScript CDNs

Importmap for Rails downloads and vendors your npm package dependencies via JavaScript CDNs that provide pre-compiled distribution versions.

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 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 and jsdelivr.com.

./bin/importmap pin react
Pinning "react" to vendor/react.js via download from https://ga.jspm.io/npm:[email protected]/index.js
Pinning "object-assign" to vendor/object-assign.js via download from https://ga.jspm.io/npm:[email protected]/index.js

This will produce pins in your config/importmap.rb like so:

pin "react" # https://ga.jspm.io/npm:[email protected]/index.js
pin "object-assign" # https://ga.jspm.io/npm:[email protected]/index.js

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.

If you later wish to remove a downloaded pin:

./bin/importmap unpin react
Unpinning and removing "react"
Unpinning and removing "object-assign"

Preloading pinned modules

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 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.

Example:

# config/importmap.rb
pin "@github/hotkey", to: "@github--hotkey.js" # file lives in vendor/javascript/@github--hotkey.js
pin "md5", preload: false # file lives in vendor/javascript/md5.js

# app/views/layouts/application.html.erb
<%= javascript_importmap_tags %>

# will include the following link before the importmap is setup:
<link rel="modulepreload" href="/assets/javascript/@github--hotkey.js">
...

Composing import maps

By default, Rails loads import map definition from the application's config/importmap.rb to the Importmap::Map object available at Rails.application.importmap.

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:

# my_engine/lib/my_engine/engine.rb

module MyEngine
  class Engine < ::Rails::Engine
    # ...
    initializer "my-engine.importmap", before: "importmap" do |app|
      app.config.importmap.paths << Engine.root.join("config/importmap.rb")
      # ...
    end
  end
end

And pinning JavaScript modules from the engine:

# my_engine/config/importmap.rb

pin_all_from File.expand_path("../app/assets/javascripts", __dir__)

Selectively importing modules

You can selectively import your javascript modules on specific pages.

Create your javascript in app/javascript:

// /app/javascript/checkout.js
// some checkout specific js

Pin your js file:

# config/importmap.rb
# ... other pins...
pin "checkout", preload: false

Import your module on the specific page. Note: you'll likely want to use a content_for block on the specifc page/partial, then yield it in your layout.

<% content_for :head do %>
  <%= javascript_import_module_tag "checkout" %>
<% end %>

Important: The javascript_import_module_tag should come after your javascript_importmap_tags

<%= javascript_importmap_tags %>
<%= yield(:head) %>

Include a digest of the import map in your ETag

If you're using ETags 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:

class ApplicationController < ActionController::Base
  etag { Rails.application.importmap.digest(resolver: helpers) if request.format&.html? }
end

Sweeping the cache in development and test

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.

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:

# my_engine/lib/my_engine/engine.rb

module MyEngine
  class Engine < ::Rails::Engine
    # ...
    initializer "my-engine.importmap", before: "importmap" do |app|
      # ...
      app.config.importmap.cache_sweepers << Engine.root.join("app/assets/javascripts")
    end
  end
end

Checking for outdated or vulnerable packages

Importmap for Rails provides two commands to check your pinned packages:

  • ./bin/importmap outdated checks the NPM registry for new versions
  • ./bin/importmap audit checks the NPM registry for known security issues

Supporting legacy browsers such as Safari on iOS 15

If you want to support legacy browsers that do not support import maps such as iOS 15.8.1 released on 22 Jan 2024, insert es-module-shims before javascript_importmap_tags as below.

<script async src="https://ga.jspm.io/npm:[email protected]/dist/es-module-shims.js" data-turbo-track="reload"></script>
<%= javascript_importmap_tags %>

License

Importmap for Rails is released under the MIT License.

More Repositories

1

rails

Ruby on Rails
Ruby
55,483
star
2

webpacker

Use Webpack to manage app-like JavaScript modules in Rails
Ruby
5,308
star
3

thor

Thor is a toolkit for building powerful command-line interfaces.
Ruby
5,115
star
4

jbuilder

Jbuilder: generate JSON objects with a Builder-style DSL
Ruby
4,324
star
5

spring

Rails application preloader
Ruby
2,804
star
6

jquery-ujs

Ruby on Rails unobtrusive scripting adapter for jQuery
JavaScript
2,607
star
7

rails-dev-box

A virtual machine for Ruby on Rails core development
Shell
2,050
star
8

solid_queue

Database-backed Active Job backend
Ruby
1,709
star
9

tailwindcss-rails

Ruby
1,388
star
10

kredis

Higher-level data structures built on Redis
Ruby
1,376
star
11

activeresource

Connects business objects and REST web services
Ruby
1,322
star
12

docked

Running Rails from Docker for easy start to development
Dockerfile
1,291
star
13

strong_parameters

Taint and required checking for Action Pack and enforcement in Active Model
Ruby
1,270
star
14

globalid

Identify app models with a URI
Ruby
1,195
star
15

actioncable

Framework for real-time communication over websockets
1,084
star
16

jquery-rails

A gem to automate using jQuery with Rails
Ruby
947
star
17

sprockets

Rack-based asset packaging system
Ruby
937
star
18

sass-rails

Ruby on Rails stylesheet engine for Sass
Ruby
859
star
19

propshaft

Deliver assets for Rails
Ruby
855
star
20

exception_notification

NOTICE: official repository moved to https://github.com/smartinez87/exception_notification
Ruby
841
star
21

sdoc

Standalone sdoc generator
JavaScript
822
star
22

jsbundling-rails

Bundle and transpile JavaScript in Rails with esbuild, rollup.js, or Webpack.
Ruby
819
star
23

solid_cache

A database-backed ActiveSupport::Cache::Store
Ruby
786
star
24

rails-perftest

Benchmark and profile your Rails apps
Ruby
780
star
25

activejob

Declare job classes that can be run by a variety of queueing backends
Ruby
744
star
26

activestorage

Store files in Rails applications
734
star
27

pjax_rails

PJAX integration for Rails
Ruby
667
star
28

actioncable-examples

Action Cable Examples
Ruby
663
star
29

cache_digests

Ruby
643
star
30

sprockets-rails

Sprockets Rails integration
Ruby
575
star
31

cssbundling-rails

Bundle and process CSS in Rails with Tailwind, PostCSS, and Sass via Node.js.
Ruby
568
star
32

activerecord-session_store

Active Record's Session Store extracted from Rails
Ruby
539
star
33

execjs

Run JavaScript code from Ruby
Ruby
528
star
34

rails-observers

Rails observer (removed from core in Rails 4.0)
Ruby
516
star
35

mission_control-jobs

Dashboard and Active Job extensions to operate and troubleshoot background jobs
Ruby
491
star
36

actiontext

Edit and display rich text in Rails applications
406
star
37

request.js

JavaScript
386
star
38

acts_as_list

NOTICE: official repository moved to https://github.com/swanandp/acts_as_list
Ruby
385
star
39

marcel

Find the mime type of files, examining file, filename and declared type
Ruby
383
star
40

rubocop-rails-omakase

Omakase Ruby styling for Rails
Ruby
380
star
41

actionpack-page_caching

Static page caching for Action Pack (removed from core in Rails 4.0)
Ruby
347
star
42

commands

Run Rake/Rails commands through the console
Ruby
337
star
43

ssl_requirement

NOTICE: official repository moved to https://github.com/retr0h/ssl_requirement
Ruby
315
star
44

rails-controller-testing

Brings back `assigns` and `assert_template` to your Rails tests
Ruby
303
star
45

rails-html-sanitizer

Ruby
302
star
46

open_id_authentication

NOTICE: official repository moved to https://github.com/Velir/open_id_authentication
Ruby
285
star
47

acts_as_tree

NOTICE: official repository moved to https://github.com/amerine/acts_as_tree
Ruby
281
star
48

actionpack-action_caching

Action caching for Action Pack (removed from core in Rails 4.0)
Ruby
260
star
49

in_place_editing

NOTICE: official repository moved to https://github.com/amerine/in_place_editing
Ruby
230
star
50

protected_attributes

Protect attributes from mass-assignment in ActiveRecord models.
Ruby
229
star
51

journey

A router for rails
Ruby
221
star
52

auto_complete

NOTICE: official repository moved to https://github.com/david-kerins/auto_complete
Ruby
211
star
53

dartsass-rails

Integrate Dart Sass with the asset pipeline in Rails
Ruby
206
star
54

dynamic_form

NOTICE: official repository moved to https://github.com/joelmoss/dynamic_form
Ruby
192
star
55

solid_cable

A database backed ActionCable adapter
Ruby
187
star
56

country_select

NOTICE: official repository moved to https://github.com/stefanpenner/country_select
Ruby
176
star
57

rails-dom-testing

Extracting DomAssertions and SelectorAssertions from ActionView.
Ruby
174
star
58

routing_concerns

Abstract common routing resource concerns to cut down on duplication.
Ruby
154
star
59

esbuild-rails

Bundle and transpile JavaScript in Rails with esbuild
Ruby
147
star
60

rails-contributors

The web application that runs https://contributors.rubyonrails.org
Ruby
138
star
61

rails-new

Create Rails projects with Ruby installed
Rust
125
star
62

actionmailbox

Receive and process incoming emails in Rails
125
star
63

requestjs-rails

JavaScript
119
star
64

activemodel-globalid

Serializing models to a single string makes it easy to pass references around
Ruby
90
star
65

account_location

NOTICE: official repository moved to https://github.com/bbommarito/account_location
Ruby
73
star
66

acts_as_nested_set

NOTICE: official repository moved to https://github.com/bbommarito/acts_as_nested_set
Ruby
71
star
67

iso-3166-country-select

WARNING: this repo is not maintained anymore, if you want to maintain it, please send an mail to rails-core
Ruby
70
star
68

activerecord-deprecated_finders

Ruby
68
star
69

spring-watcher-listen

Ruby
64
star
70

website

HTML
64
star
71

weblog

Superseded by https://github.com/rails/website
HTML
63
star
72

prototype-ujs

JavaScript
62
star
73

prototype_legacy_helper

WARNING: this repo is not maintained anymore, if you want to maintain it, please send an mail to rails-core
Ruby
60
star
74

verification

NOTICE: official repository moved to https://github.com/sikachu/verification
Ruby
58
star
75

prototype-rails

Add RJS, Prototype, and Scriptaculous helpers to Rails 3.1+ apps
Ruby
55
star
76

activemodel-serializers-xml

Ruby
52
star
77

record_tag_helper

ActionView Record Tag Helpers
Ruby
51
star
78

homepage

Superseded by https://github.com/rails/website
HTML
50
star
79

rollupjs-rails

Bundle and transpile JavaScript in Rails with rollup.js
Ruby
49
star
80

actionpack-xml_parser

XML parameters parser for Action Pack (removed from core in Rails 4.0)
Ruby
49
star
81

activesupport-json_encoder

Ruby
48
star
82

etagger

Declare what goes in to your ETags: asset versions, account ID, etc.
Ruby
41
star
83

upload_progress

NOTICE: official repository moved to https://github.com/rishav/upload_progress
Ruby
39
star
84

devcontainer

Shell
38
star
85

atom_feed_helper

NOTICE: official repository moved to https://github.com/TrevorBramble/atom_feed_helper
Ruby
38
star
86

render_component

NOTICE: official repository moved to https://github.com/malev/render_component. Components allow you to call other actions for their rendered response while executing another action
Ruby
38
star
87

gsoc2014

Project website and wiki for Ruby on Rails proposals to Google Summer of Code 2014
37
star
88

gsoc2013

Project website and wiki for Ruby on Rails proposals to Google Summer of Code 2013
31
star
89

ruby-coffee-script

Ruby CoffeeScript Compiler
Ruby
28
star
90

asset_server

NOTICE: official repository moved to https://github.com/andhapp/asset_server
Ruby
27
star
91

homepage-2011

This repo is now legacy. New homepage is at rails/homepage
HTML
27
star
92

deadlock_retry

NOTICE: official repository moved to https://github.com/heaps/deadlock_retry
Ruby
27
star
93

rails-docs-server

Ruby
25
star
94

token_generator

NOTICE: official repository moved to https://github.com/bbommarito/token_generator
Ruby
25
star
95

http_authentication

NOTICE: official repository moved to https://github.com/dshimy/http_authentication
Ruby
22
star
96

irs_process_scripts

WARNING: this repo is not maintained anymore, if you want to maintain it, please send an mail to rails-core. The extracted inspector, reaper, and spawner scripts from script/process/*
22
star
97

javascript_test

WARNING: this repo is not maintained anymore, if you want to maintain it, please send an mail to rails-core
JavaScript
19
star
98

buildkite-config

Fallback configuration for branches that lack a .buildkite/ directory
Ruby
18
star
99

scriptaculous_slider

WARNING: this repo is not maintained anymore, if you want to maintain it, please send an mail to rails-core
JavaScript
18
star
100

request_profiler

WARNING: this repo is not maintained anymore, if you want to maintain it, please send an mail to rails-core. Request profiler based on integration test scripts
Ruby
17
star