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.

Sorry about this! The docs say it should work out of the box, but this is currently only the case if your node_modules folder is in your project root, but most people have it in assets. We have an open PR that should be released soon to make this smoother: allow auto-symlinking node_modules for ColocatedJS by SteffenDE · Pull Request #3988 · phoenixframework/phoenix_live_view · GitHub

5 Likes

Thanks! @steffend

This should work out of the box now if you update to LiveView 1.1.12! Phoenix.LiveView.ColocatedJS — Phoenix LiveView v1.1.12

1 Like