egoist / tsup

The simplest and fastest way to bundle your TypeScript libraries.
https://tsup.egoist.dev
MIT License
8.46k stars 209 forks source link

TypeError: __require.resolve is not a function #1135

Open moltar opened 1 month ago

moltar commented 1 month ago

This error is thrown by Vitest, when running tests against a project using a package compiled by tsup.

TypeError: __require.resolve is not a function

The bundled code of lib/index.mjs looks like this:

var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
  get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
}) : x)(function(x) {
  if (typeof require !== "undefined")
    return require.apply(this, arguments);
  throw Error('Dynamic require of "' + x + '" is not supported');
});

Here's the tsup.config.json that was used to build the library:

{
  "clean": true,
  "sourcemap": true,
  "watch": false,
  "silent": true,
  "entry": [
    "src/index.ts"
  ],
  "dts": {
    "resolve": true
  },
  "tsconfig": "tsconfig.build.json",
  "outDir": "lib",
  "format": [
    "cjs",
    "esm"
  ],
  "shims": true,
  "target": "node18.19.0"
}

I'm wondering why is that tsup not shimming the require.resolve correctly?

Adding this shim myself, before using require works correctly:

const require_ = createRequire(
  __filename ??
    // @ts-expect-error Forward compat. The `import.meta` meta-property is only allowed when the '--module' option is 'es2020', 'es2022', 'esnext', 'system', 'node16', or 'nodenext'.
    import.meta.url,
)

Package versions:

tsup 8.0.2
├─┬ bundle-require 4.0.2
│ └── esbuild 0.19.12 peer
└── esbuild 0.19.12

Related Issues

Upvote & Fund

Fund with Polar

moltar commented 1 month ago

Shall there be a shim in this file, perhaps to shim for require?

https://github.com/egoist/tsup/blob/00188a0dc848c48fac45de245d1e021f370a84a3/assets/esm_shims.js#L1-L9