How to import a nodejs module in colocated hooks

I have a hook that depends on hls.js that I’m trying to make colocated

import Hls from 'hls.js'; line throws an error:

[ERROR] Could not resolve "hls.js"
You can mark the path "hls.js" as external to exclude it from the bundle, which will remove this error.

Adding --external:hls.js to the esbuild args also throws a console error:
Uncaught Error: Dynamic require of "hls.js" is not supported

Is there a way to have import statements in colocated hooks?

2 Likes

Same question - have a small library I’d like to use for some fuzzy searching and it works from a CDN script tag, but hoping to import this.

Update:

As a temporary fix, I moved the colocated js into node_modules so I can make a relative import:

config.ex

config :phoenix_live_view, :colocated_js,
  target_directory: Path.expand("../assets/node_modules/phoenix-colocated", __DIR__)

liveview.ex

import Hls from "../../../hls.js/dist/hls.mjs";
...

@cochranjd You can try something similar for now

It works if I npm install into my home directory with `npm install –save`

The docs say it should be possible to import from node_modules but they aren’t perfectly clear on which folder is meant there. I would think it should be the one in assets so maybe its a bug.

Edit: I previously thought it was node_modules next to the component file which was wrong.