TypeError: __require.resolve is not a function
- Dominant language
- TypeScript
- Stars
- 11.3k
- Forks
- 275
- PR merge metrics
- No merged PRs in 30d
Description
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:
```js
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:
```json
{
"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:
```ts
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:
```plain
tsup 8.0.2
├─┬ bundle-require 4.0.2
│ └── esbuild 0.19.12 peer
└── esbuild 0.19.12
```
## Related Issues
- `tsup` issue that says it was fixed: https://github.com/egoist/tsup/issues/369
- Suggested shim in `esbuild`: https://github.com/evanw/esbuild/issues/1921#issuecomment-1898197331
Contributor guide
Research direction
Start with the generated lib/index.mjs and the tsup.config.json entry using src/index.ts and tsconfig.build.json, then compare the ESM shim with the related esbuild and tsup issues. Reproduce the failure in Vitest with the supplied package configuration; done means require.resolve works for the bundled library without a consumer-provided shim.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- node.js, typescript
- Domain
- build-system, testing
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100