2

In rails 6 with webpacker you could throw in a <%= javascript_pack_tag 'alerts' %> in a view or template to inject some js.

How does this work with import maps and rails 7?

1 Answer 1

3

As long as the code is correctly in the import map, you can reference it with:

<script type="module">import "/assets/custom/alerts.js";</script>

Presuming the file is app/javascript/custom/alerts.js

Referenced in config/importmap.rb as:

pin_all_from "app/javascript/custom", under: "custom"

And imported into the application.js:

import "custom/alerts"

Edit: I now think this is an antipattern 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>
Sign up to request clarification or add additional context in comments.

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.