0
0
Ruby on Railsframework~5 mins

Import maps (Rails 7+)

Choose your learning style9 modes available
Introduction

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.

You want to add JavaScript to a Rails app without setting up Webpack or other bundlers.
You want to keep your app simple and avoid complex JavaScript build steps.
You want to load JavaScript modules from CDNs or local files easily.
You want to quickly prototype JavaScript features in Rails.
You want to manage JavaScript dependencies declaratively in Rails.
Syntax
Ruby on Rails
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.

Examples
This pins a local module named "application" and an external module "lodash" from a CDN.
Ruby on Rails
importmap pin "application"
importmap pin "lodash", to: "https://cdn.skypack.dev/lodash"
Imports the debounce function from the pinned "lodash" module and uses it.
Ruby on Rails
// In app/javascript/application.js
import { debounce } from "lodash"
debounce(() => console.log('Hello'), 300)
This Rails helper inserts the necessary script tags to load the import map and modules in your HTML.
Ruby on Rails
<%= javascript_importmap_tags %>
Sample Program

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.

Ruby on Rails
// 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>
OutputSuccess
Important Notes

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.

Summary

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