Import maps let you use JavaScript modules in Rails without needing extra build tools. They help your app load JavaScript files directly in the browser.
Import maps (Rails 7+)
importmap pin "module-name" [to: "url-or-path"] // In your JavaScript file: import { something } from "module-name" // In your Rails layout: <%= javascript_importmap_tags %>
The importmap pin command registers a JavaScript module with a name and optional URL or path.
Use javascript_importmap_tags helper in your layout to load the import map and modules.
importmap pin "application" importmap pin "lodash", to: "https://cdn.skypack.dev/lodash"
debounce function from the pinned "lodash" module and uses it.// In app/javascript/application.js import { debounce } from "lodash" debounce(() => console.log('Hello'), 300)
<%= javascript_importmap_tags %>
This example shows how to pin modules in importmap.rb, import and use a function from lodash in application.js, and include the import map tags in the Rails layout. When you click the button, it alerts "Clicked!" with a debounce delay.
// config/importmap.rb importmap pin "application" importmap pin "lodash", to: "https://cdn.skypack.dev/lodash" // app/javascript/application.js import { debounce } from "lodash" window.onload = () => { const button = document.getElementById('btn') button.addEventListener('click', debounce(() => alert('Clicked!'), 500)) } // app/views/layouts/application.html.erb <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Importmap Demo</title> <%= javascript_importmap_tags %> </head> <body> <button id="btn">Click me</button> </body> </html>
Import maps work best for small to medium JavaScript needs without complex bundling.
You can update pinned modules by running bin/importmap pin commands.
Remember to restart your Rails server after changing importmap configuration.
Import maps let Rails apps load JavaScript modules without bundlers.
Use importmap pin to register modules and javascript_importmap_tags to load them.
This keeps JavaScript simple and easy to manage in Rails 7+.