Trouble Loading an ES Module

Is there something I’m doing wrong here? This module is not working in Observable, but it works in a browser with a script tag.

This is the error i see.

But this code works in a browser.

    <script type="module">
      import {Client} from "/dist/esm/index.mjs"
      const zealot = await import(
      const client = new zealot.Client("")
      const pools = await client.query("from :pools").then((r) => r.js())

I used esbuild to build the bundle from a standard typescript project.

esbuild src/esm/index.ts --bundle --outfile=dist/esm/index.mjs --format=esm

You can import their esm build directly:

zealot = import("")

I do see lodash bundled in that file, so I would guess that their build is broken (something about __toESM() perhaps?). You may want to file an issue in their repo.


It’s not __toESM(), but the bundling of lodash itself. From what I can tell the module wrapper looks for an AMD module loader and then uses that one. As a result, require_lodash() returns an empty object.

Observable’s Standard Library loads dependencies lazily via d3-require, an AMD/UMD module loader. The loader registers itself while zealot is fetched. To prove that, we can run the following code:

  // wait for AMD dependencies to load.
  await Promises.delay(2000);
  // "Unregister" the load callback.
  delete window.define;
  // Load the rest.
  const zealot = await import("");
  const client = new zealot.Client("");
  const pool = await client.query("from :pools").then((r) => r.js());
  return pool;

Which then gives us the expected error (due to the missing token):

I recommend to patch the module on-the-fly to get rid of the AMD loader detection:

import {importPatched} from "@mootari/patched-imports"
zealot = importPatched(
  src => src.replace(/\btypeof define\b/g, "null")

Full example:

Thank you so much. That was it. I removed lodash from the bundle and it started working.I appreciate it!

1 Like

@jameskerr Great to hear! You can mark the topic as solved by clicking the checkmark under the reply that answered your question:

1 Like