Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TypeError: __require.resolve is not a function #1135

Open
moltar opened this issue Jun 1, 2024 · 1 comment
Open

TypeError: __require.resolve is not a function #1135

moltar opened this issue Jun 1, 2024 · 1 comment

Comments

@moltar
Copy link

moltar commented Jun 1, 2024

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

  • We're using Polar.sh so you can upvote and help fund this issue.
  • We receive the funding once the issue is completed & confirmed by you.
  • Thank you in advance for helping prioritize & fund our backlog.
Fund with Polar
@moltar
Copy link
Author

moltar commented Jun 1, 2024

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

// Shim globals in esm bundle
import { fileURLToPath } from 'url'
import path from 'path'
const getFilename = () => fileURLToPath(import.meta.url)
const getDirname = () => path.dirname(getFilename())
export const __dirname = /* @__PURE__ */ getDirname()
export const __filename = /* @__PURE__ */ getFilename()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant