0
0
Ruby on Railsframework~30 mins

Import maps (Rails 7+) - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Import Maps in Rails 7+
📖 Scenario: You are building a simple Rails 7 application that uses import maps to manage JavaScript modules without a bundler. This helps you load JavaScript files easily and keep your app organized.
🎯 Goal: Create a Rails 7 app setup that uses import maps to load a custom JavaScript module and display a greeting message on the page.
📋 What You'll Learn
Create a JavaScript module file with a greeting function
Add the JavaScript module to the import map configuration
Import and use the module in the application JavaScript
Include the JavaScript in the Rails layout to run on page load
💡 Why This Matters
🌍 Real World
Import maps let Rails apps manage JavaScript modules without complex bundlers, making it easier to add and update JS code.
💼 Career
Understanding import maps is important for modern Rails developers to efficiently organize and load JavaScript in their applications.
Progress0 / 4 steps
1
Create a JavaScript module with a greeting function
Create a file called app/javascript/greeting.js with a function named sayHello that returns the string 'Hello from import maps!'. Export the function as a named export.
Ruby on Rails
Need a hint?

Use export function sayHello() to define and export the function.

2
Add the greeting module to the import map
Add the greeting module to the import map by running the command bin/importmap pin greeting in your terminal. Then, open config/importmap.rb and verify it contains pin "greeting", to: "greeting.js".
Ruby on Rails
Need a hint?

Use the bin/importmap pin greeting command to add the module to the import map.

3
Import and use the greeting module in application.js
In app/javascript/application.js, import the sayHello function from the greeting module. Then, call sayHello() and assign its result to a constant named message.
Ruby on Rails
Need a hint?

Use import { sayHello } from "greeting" to import the function.

4
Display the greeting message on the page
In app/views/layouts/application.html.erb, add the javascript_importmap_tags helper inside the <head> tag to load the JavaScript. Then, in app/javascript/application.js, add code to insert the message text inside an element with id greeting when the page loads.
Ruby on Rails
Need a hint?

Use <%= javascript_importmap_tags %> in the HTML head and add a DOMContentLoaded event listener in JavaScript.