README.md in importmap-rails-1.2.3 vs README.md in importmap-rails-2.0.0

- old
+ new

@@ -2,11 +2,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. 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. -There's [native support for import maps in Chrome/Edge 89+/Firefox 108+](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. +[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). ## Installation Importmap for Rails is automatically included in Rails 7+ for new applications, but you can also install it manually in existing applications: @@ -14,10 +14,19 @@ 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: + +```ruby +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: @@ -55,24 +64,23 @@ ## 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. 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`. +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. +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. ```rb # config/importmap.rb -pin_all_from 'app/javascript/src`, under: 'src', to: 'src' +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: @@ -85,95 +93,16 @@ 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 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. +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](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). -It works like so: - ```bash -./bin/importmap pin react react-dom -Pinning "react" to https://ga.jspm.io/npm:react@17.0.2/index.js -Pinning "react-dom" to https://ga.jspm.io/npm:react-dom@17.0.2/index.js -Pinning "object-assign" to https://ga.jspm.io/npm:object-assign@4.1.1/index.js -Pinning "scheduler" to https://ga.jspm.io/npm:scheduler@0.20.2/index.js - -./bin/importmap json - -{ - "imports": { - "application": "/assets/application-37f365cbecf1fa2810a8303f4b6571676fa1f9c56c248528bc14ddb857531b95.js", - "react": "https://ga.jspm.io/npm:react@17.0.2/index.js", - "react-dom": "https://ga.jspm.io/npm:react-dom@17.0.2/index.js", - "object-assign": "https://ga.jspm.io/npm:object-assign@4.1.1/index.js", - "scheduler": "https://ga.jspm.io/npm:scheduler@0.20.2/index.js" - } -} -``` - -As you can see, the two packages react and react-dom resolve to a total of four dependencies, when resolved via the jspm default. - -Now you can use these in your application.js entrypoint like you would any other module: - -```js -import React from "react" -import ReactDOM from "react-dom" -``` - -You can also designate a specific version to pin: - -```bash -./bin/importmap pin react@17.0.1 -Pinning "react" to https://ga.jspm.io/npm:react@17.0.1/index.js -Pinning "object-assign" to https://ga.jspm.io/npm:object-assign@4.1.1/index.js -``` - -Or even remove pins: - -```bash -./bin/importmap unpin react -Unpinning "react" -Unpinning "object-assign" -``` - -If you pin a package that has already been pinned, it'll be updated inline, along with its dependencies. - -You can control the environment of the package for packages with separate "production" (the default) and "development" builds: - -```bash -./bin/importmap pin react --env development -Pinning "react" to https://ga.jspm.io/npm:react@17.0.2/dev.index.js -Pinning "object-assign" to https://ga.jspm.io/npm:object-assign@4.1.1/index.js -``` - -You can also pick an alternative, supported CDN provider when pinning, like `unpkg` or `jsdelivr` (`jspm` is the default): - -```bash -./bin/importmap pin react --from jsdelivr -Pinning "react" to https://cdn.jsdelivr.net/npm/react@17.0.2/index.js -``` - -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. - -Run `./bin/importmap` to see all options. - -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`: - -```ruby -pin "react", to: "https://cdn.skypack.dev/react" -``` - - -## Downloading vendor files from the JavaScript CDN - -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: - -```bash -./bin/importmap pin react --download +./bin/importmap pin react Pinning "react" to vendor/react.js via download from https://ga.jspm.io/npm:react@17.0.2/index.js Pinning "object-assign" to vendor/object-assign.js via download from https://ga.jspm.io/npm:object-assign@4.1.1/index.js ``` This will produce pins in your `config/importmap.rb` like so: @@ -183,37 +112,34 @@ pin "object-assign" # https://ga.jspm.io/npm:object-assign@4.1.1/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, you again pass `--download`: +If you later wish to remove a downloaded pin: ```bash -./bin/importmap unpin react --download +./bin/importmap unpin react Unpinning and removing "react" Unpinning and removing "object-assign" ``` -Just like with a normal pin, you can also update a pin by running the `pin --download` command again. - - ## 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 supports [modulepreload links](https://developers.google.com/web/updates/2017/12/modulepreload). Pinned modules can be preloaded by appending `preload: true` to the pin. +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. Example: ```ruby # config/importmap.rb -pin "@github/hotkey", to: "https://ga.jspm.io/npm:@github/hotkey@1.4.4/dist/index.js", preload: true -pin "md5", to: "https://cdn.jsdelivr.net/npm/md5@2.3.0/md5.js" +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="https://ga.jspm.io/npm:@github/hotkey@1.4.4/dist/index.js"> +<link rel="modulepreload" href="/assets/javascript/@github--hotkey.js"> ... ``` ## Composing import maps @@ -258,11 +184,11 @@ Pin your js file: ```rb # config/importmap.rb # ... other pins... -pin "checkout" +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. ```erb @@ -307,19 +233,9 @@ app.config.importmap.cache_sweepers << Engine.root.join("app/assets/javascripts") end end end ``` - -## Expected errors from using the es-module-shim - -While import maps are native in Chrome, Edge, and Firefox, 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. - -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. - -## Turning off the shim - -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+/firefox 108+. But you really shouldn't have to, as the shim is designed to gracefully work with natively compatible drivers. ## 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