Managing External JS Dependencies in Rails

It is hard to beat Sean P Doyle’s pithy advice on how to manage external JS dependencies.

When you are writing JS code, you might say to the server “use dayjs”. Then the server might ask: “where do I get that from?”. And you must have an answer.

If your project has an external dependency, you have several options.

First, declare the import statement in the module that needs it: import day from “dayjs”.

Next, configure your server so that it knows how to resolve the dayjs package name. You have several options, including:

  • (1) downloading the source as a vendored package or a gem that bundles its assets, configuring how to resolve the name in your importmap.json with a project-relative path (e.g. “dayjs”: asset_path(“dayjs/dayjs.min.js”)), then serving it from the Rails application
  • (2) downloading the source as a node_modules package, configuring how to resolve the name in your importmap.json with a project-relative Webpacker path (e.g. “dayjs”: asset_pack_path(“dayjs/dayjs.min.js”)), then serving it from the Rails application
  • (3) configuring how to resolve the name in your importmap.json with an absolute URL (e.g. “dayjs”: “https://cdn.skypack.dev/dayjs”)
  • (4) declaring the import statement directly in your module with an absolute URL (e.g. import day from “https://cdn.skypack.dev/dayjs”)
Written on February 16, 2025