Home > front end >  Can't import custom JavaScript files with importmaps in Rails 7
Can't import custom JavaScript files with importmaps in Rails 7

Time:01-21

I am trying to learn about Rails 7 and import maps, and I am following this tutorial by DHH: https://www.youtube.com/watch?v=PtxZvFnL2i0

The video is about a year old, and based on an alpha version of Rails 7, but it works up to a point. Now I'm at that point and struggling to figure out what's changed or what needs to change.

I followed along til ~17:18 where he adds Vue.js to the demo. This is the first time he adds a JS file that's custom to the application, instead of importing a library. In the tutorial, he adds the following line to application.js:

import "comps/vue_components"

That line fails in my implementation with the following JS error:

Uncaught TypeError: Failed to resolve module specifier "comps/vue_components". Relative references must start with either "/", "./", or "../".

I tried updating the line to the following to resolve the error:

import "./comps/vue_components"

but that just fails silently. It looks like it's killing the execution of javascript altogether - if I put a console.log statement into application.js, it only shows in the console if I omit or comment out the line to import the vue component.

Here is my config/importmap.rb file:

# Pin npm packages by running ./bin/importmap

pin "application", preload: true
pin "@hotwired/turbo-rails", to: "turbo.min.js", preload: true
pin "@hotwired/stimulus", to: "stimulus.min.js", preload: true
pin "@hotwired/stimulus-loading", to: "stimulus-loading.js", preload: true
pin_all_from "app/javascript/controllers", under: "controllers"

pin "trix"
pin "@rails/actiontext", to: "actiontext.js"

pin "md5", to: "https://cdn.skypack.dev/md5"

pin "vue", to: "https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.esm.browser.js"

pin_all_from "app/javascript/components", under: "comps"

this is my application.js file:

// Configure your import map in config/importmap.rb. Read more: https://github.com/rails/importmap-rails
import "@hotwired/turbo-rails"
import "controllers"
import "trix"
import "@rails/actiontext"
import "./comps/vue_components"
console.log('hello')

The git project is located here: https://github.com/fredwillmore/showntell

CodePudding user response:

That video is not a tutorial, "alpha preview" is what it says in the title. You should find something up to date, lots of changes happened since then. But to fix your issue, do this:

pin_all_from "app/javascript/components", under: "comps", to: "components"

Do not use relative imports. Do not precompile. I have a more detailed answer about this:

https://stackoverflow.com/a/72855705/207090


You should upgrade your ruby to the latest version. Don't start anything new with 2.7.2.

  • Related