Search code examples
javascriptruby-on-railsruby-on-rails-7import-maps

Rails 7 Import Maps - How do I inject a script into HTML template?


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?


Solution

  • 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>