JGleason
JGleason

Reputation: 3946

How do I handle ESM dependencies of dependencies in the browser (without UMD)?

I have one project that I rollup into a file. The final file looks something like this...

import {SomeClass} from "another-lib";
export class Thing{
  ...
}

Then I try to load like

<script type="module" src="myHostedVersion.mjs">

Then problem I have is because I am not using a precompiler when I try to load it into the browser it complains about needing to start with ./ or /.

So the question is, how do I load this properly from the browser (assuming I host the MJS)? Do I have to rewrite the path using rollup or is there a cleaner option? I currently work around by loading into the window.

Upvotes: 1

Views: 1016

Answers (2)

NotWoods
NotWoods

Reputation: 842

The browser can't resolve module names that aren't relative paths like "another-lib". There are a few different workarounds:

  1. Rollup can bundle this module and output a single Javascript file. Using output.format: 'es' will create a module file that doesn't look ugly.

  2. You can import the module from Pika CDN using an HTTPS URL.

import {SomeClass} from "https://cdn.pika.dev/another-lib";
export class Thing{
  ...
}
  1. You can use a tool like Snowpack to create additional files for just your external modules.
import {SomeClass} from "../web_modules/another-lib.js";
export class Thing{
  ...
}

Upvotes: 0

JGleason
JGleason

Reputation: 3946

The answer for me was to either create a "fat" UMD js file with the resolve plugin for rollup (ugly) or Just import the project and because it attached itself to window I could access it that way. Then I just put in a null check to make sure it is on window.

Upvotes: 0

Related Questions