How to Use Importmap in Rails: Simple Setup and Usage
In Rails, you use
importmap to manage JavaScript modules without a bundler by adding dependencies in config/importmap.rb and referencing them in your JavaScript files with import statements. Rails loads these modules directly in the browser using native ES module support.Syntax
The main parts of using importmap in Rails are:
pin: Registers a JavaScript package or file inconfig/importmap.rb.import: Used in JavaScript files to load the pinned modules.javascript_importmap_tags: Helper in Rails views to load the importmap and modules.
ruby
pin "application", to: "application.js" pin "lodash", to: "https://cdn.skypack.dev/lodash"
Example
This example shows how to pin a JavaScript library and use it in your Rails app with importmap.
ruby and javascript and erb
# config/importmap.rb pin "lodash", to: "https://cdn.skypack.dev/lodash" // app/javascript/application.js import _ from "lodash" console.log(_.join(["Hello", "Rails", "Importmap"], " ")) <!-- app/views/layouts/application.html.erb --> <%= javascript_importmap_tags %>
Output
Hello Rails Importmap
Common Pitfalls
Common mistakes when using importmap in Rails include:
- Not pinning the JavaScript package in
config/importmap.rb. - Forgetting to include
<%= javascript_importmap_tags %>in your layout. - Trying to use packages that require bundling or Node.js features, which importmap does not support.
Always check if the package works as an ES module in the browser.
javascript and ruby
## Wrong: Using a package without pinning it // app/javascript/application.js import _ from "lodash" // Error: lodash not found ## Right: Pinning lodash first # config/importmap.rb pin "lodash", to: "https://cdn.skypack.dev/lodash" // app/javascript/application.js import _ from "lodash"
Quick Reference
| Command | Purpose |
|---|---|
| pin "package", to: "url_or_path" | Register a JS package or file in importmap |
| import packageName from "package" | Import the pinned package in JS files |
| <%= javascript_importmap_tags %> | Include importmap scripts in Rails views |
| bin/importmap pin package | CLI command to add packages automatically |
Key Takeaways
Pin JavaScript packages in config/importmap.rb before importing them in your JS files.
Use <%= javascript_importmap_tags %> in your layout to load importmap scripts.
Importmap works best with ES modules that run natively in browsers without bundlers.
Avoid packages that require Node.js or bundling tools when using importmap.
Use the Rails CLI command bin/importmap pin to add packages easily.