javascriptruby-on-railsrubygemsasset-pipelinesprockets

Sprockets //= require with jsbundling-rails (esbuild) - how to include JS provided by gem?


Basically, exactly as the title says. I have a gem installed that gives me some JS to use. This wasn't a problem before as I was using Sprockets + Assets pipeline.

Now, I migrated to jsbundling-rails and have literally no idea how to include that JS code provided by gem. I've spent like 10 hours searching and no luck so far.

Please, help me.


Solution

  • The gem would have to have a js package that can be installed with yarn/npm so that it can be imported in application.js. If it doesn't, you can setup a js file to be processed only by sprockets, like in the old days.

    Add another javascript entry point that will skip esbuild and will be processed only by sprockets.

    Update manifest:

    // app/assets/config/manifest.js
    
    //= link custom.js
    

    Add //= require directive:

    // app/assets/javascripts/custom.js
    
    //= require gem_javascript
    

    Add it to layout:

    <!-- app/views/layouts/application.html.erb -->
    
    <%= javascript_include_tag "application", "custom", "data-turbo-track": "reload", defer: true %>
    

    Alternatively, instead of using //= require add gem_javascript to javascript_include_tag:

    <%= javascript_include_tag "application", "gem_javascript", "data-turbo-track": "reload", defer: true %>
    

    Might have to add it to manifest as well for precompilation:

    // app/assets/config/manifest.js
    
    //= link gem_javascript