Search code examples
node.jsruby-on-railsruby-on-rails-7import-maps

404 error when importing npm yaml package into Rails 7


I'm trying to import the yaml npm package into a Rails 7 app; but, I appear to be missing a step. When I attempt to load a page that imports this package, I get this 404:

Started GET "/_/9e35e2fa.js" for ::1 at 2023-08-28 09:56:58 -0400
  
ActionController::RoutingError (No route matches [GET] "/_/9e35e2fa.js"):

When I look in the network tab of the developer tools, I see that the initiator of this file is yaml-c3a2c347f0aeaabd61d2e4bfa7779882d85af0a207269ec0727fd8c981c75a4a.js

To add this npm package, I did the following:

  • npm install yaml
  • ./bin/importmap pin yaml --download
  • restart the server (development)

Am I missing a step?

I'm using Rails 7.0.7 and Ruby 3.1.2


Solution

  • You're using importmaps, npm install yaml is not involved in that. You shouldn't download pinned packages by default, it almost defeats the purpose of importmaps. CDN for other people's stuff, local files for your stuff.

    # undo your download, make sure it's not in vendor/javascript
    $ bin/importmap unpin yaml
    
    # pin to the url
    $ bin/importmap pin yaml
    Pinning "yaml" to https://ga.jspm.io/npm:yaml@2.3.1/browser/index.js
    

    Either they meant for it to work that way, or they missed a file. But that relative import /_/9e35e2fa.js has to be relative to jspm, which should work fine now:
    https://ga.jspm.io/npm:yaml@2.3.1/_/9e35e2fa.js


    Update

    Once you open the page once, everything is cached in browser, just don't hard reload or clear cache.

    But you can also fix yaml package to work when you download it:

    # config/importmap.rb
    
    if Rails.env.production?
      pin "yaml", to: "https://ga.jspm.io/npm:yaml@2.3.1/browser/index.js"
    else
      pin "yaml" # @2.3.1
      pin "/_/9e35e2fa.js", to: "9e35e2fa.js"
    end
    
    bin/importmap pin yaml --download
    wget -P vendor/javascript/ https://ga.jspm.io/npm:yaml@2.3.1/_/9e35e2fa.js