I am building a website with Ruby on Rails, and I encountered a problem with including my javascript files into project. I have a script named init.js
in app/javascript
directory, and I want it to be included in all my views.
If I got it right, I need to use Asset Pipeline for this, so I wrote //= require init
in the app/javascript/application.js
file. However, when I go on the website, I can see, that application.js
is included in the sources tab, but init.js
is not:
Also I tried to write <%= javascript_include_tag "init" %>
in my layout head, and it worked, but if I understand correctly, it doesn't use Asset Pipeline, so it's not what I want.
By the way, asset pipeline worked as expected with CSS files: I just put all my CSS into app/assets/stylesheets
, and contents of all files got copied into application.css
, where I have *= require_tree .
.
Here's contents of some files:
app/assets/config/manifest.js
:
//= link_tree ../images
//= link_directory ../stylesheets .css
//= link_tree ../../javascript .js
//= link_tree ../../../vendor/assets/javascript .js
//= link_tree ../../../vendor/assets/stylesheets .css
app/javascript/application.js
:
import "@hotwired/turbo-rails"
import "controllers"
//= require init
What am i missing?
You have to create an import-map, then use it to import your file:
# config/importmap.rb
pin "init"
$ bin/importmap json
{
"imports": {
"application": "/assets/application-4edf77fd1c5995d5aa4823aefad1ca4255db06546e3f9142669570c749d6b119.js",
"@hotwired/turbo-rails": "/assets/turbo-6f8f1796078d2d3f7cb9b6badcd2d5e76287a3c58d97baffaa59dd12bd4135f5.js",
"@hotwired/stimulus": "/assets/stimulus-f75215805563870a61ee9dc5a207ce46d4675c7e667558a54344fd1e7baa697f.js",
"@hotwired/stimulus-loading": "/assets/stimulus-loading-3576ce92b149ad5d6959438c6f291e2426c86df3b874c525b30faad51b0d96b3.js",
"init": "/assets/init-04024382391bb910584145d8113cf35ef376b55d125bb4516cebeb14ce788597.js",
...
# ^ these are imports ^ these are urls, handled by sprockets (aka asset pipeline)
// app/javascript/application.js
import "init"
For all the details: https://stackoverflow.com/a/72855705/207090