lucacasonato / esbuild_deno_loader

Deno module resolution for `esbuild`
https://jsr.io/@luca/esbuild-deno-loader
MIT License
176 stars 46 forks source link

Resolver dies on `try { require() } catch {}` #150

Open lowlighter opened 1 month ago

lowlighter commented 1 month ago

Trying to bundle something with JSDOM but it fails because it attempts to load "canvas":

// https://github.com/jsdom/jsdom/blob/04541b377d9949d6ab56866760b7883a23db0577/lib/jsdom/utils.js#L101-L105
function example() {
  try {
    exports.Canvas = require("canvas");
  } catch {
    exports.Canvas = null;
  }
}

Error:

      3 │     exports.Canvas = require("canvas");
        ╵                              ~~~~~~~~

error: Uncaught (in promise) Error: Build failed with 1 error:

- ERROR: [plugin: deno-resolver] Relative import path "canvas" not prefixed with / or ./ or ../ and not in import map from

Reproduction


import * as esbuild from "npm:esbuild@0.24.0";
import { denoPlugins } from "jsr:@luca/esbuild-deno-loader@^0.11.0";
import { encodeBase64 } from "jsr:@std/encoding/base64"

console.log(await esbuild.build({
  plugins: [...denoPlugins()],
  entryPoints: [`data:application/typescript;base64,${encodeBase64(example.toString())}`],
  write: false,
  bundle: true,
  format: "esm",
}))

// https://github.com/jsdom/jsdom/blob/04541b377d9949d6ab56866760b7883a23db0577/lib/jsdom/utils.js#L101-L105
function example() {
  try {
    exports.Canvas = require("canvas");
  } catch {
    exports.Canvas = null;
  }
}

___

Workaround:

Alias `canvas` to `node:canvas` (possibly related to #137) in import map and declare `node:canvas` as "external" (else without external, you get `Unknown built-in "node:" module: canvas` error)