8

playing around with Rails 7 and import maps. Trying to import a folder with some custom JS.

# config/importmap.rb
pin_all_from "app/javascript/custom", under: "custom"

# app/javascript/application.js
import "custom"

Gives Uncaught TypeError: Failed to resolve module specifier "custom" on Chrome and Uncaught Error: Unable to resolve specifier 'custom' from [shim] on Firefox

interestingly import "custom/script" works fine.

what am I doing wrong?

1
  • import "custom/script" also throws an error for me (Firefox). Commented Mar 31, 2022 at 19:58

2 Answers 2

7

I had this same problem and found the following solution:

# app/javascript/application.js
import "custom/my_custom_code.js"

This means that pin_all_from "app/javascript/custom", under: "custom" is really just making each custom JS file available under the custom namespace. Therefore, you still need to import each file individually.

Sign up to request clarification or add additional context in comments.

Comments

-4

While this might still be a valid thing to do in some use cases, I think what I was trying to do was a bit of an anti-pattern in Rails 7.

It is very easy to use Stimulus controllers instead.

Stimulus Handbook For reference

For example, to dismiss an alert when a user clicks the "x"

// app/javascript/alerts_controller.js
import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
    dismiss () {
        this.element.style.display = 'none';
    }
}
<div data-controller="alerts">
    <h2> Alert! </h2>
    <span data-action="click->alerts#dismiss"><i class="fas fa-times"></i></span>
</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.