简体   繁体   中英

Rails 7 Import Maps - import folder with custom scripts

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?

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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM