Skip to content

Make esbuild require hack look better in output #56060

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

Merged
merged 2 commits into from
Nov 3, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 8 additions & 4 deletions Herebyfile.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -217,18 +217,22 @@ function createBundler(entrypoint, outfile, taskOptions = {}) {
// to be consumable by other bundlers, we need to convert these calls back to
// require so our imports are visible again.
//
// The leading spaces are to keep the offsets the same within the files to keep
// source maps working (though this only really matters for the line the require is on).
// To fix this, we redefine "require" to a name we're unlikely to use with the
// same length as "require", then replace it back to "require" after bundling,
// ensuring that source maps still work.
//
// See: https://github.com/evanw/esbuild/issues/1905
options.define = { require: "$$require" };
const require = "require";
const fakeName = "Q".repeat(require.length);
const fakeNameRegExp = new RegExp(fakeName, "g");
options.define = { [require]: fakeName };
options.plugins = [
{
name: "fix-require",
setup: build => {
build.onEnd(async () => {
let contents = await fs.promises.readFile(outfile, "utf-8");
contents = contents.replace(/\$\$require/g, " require");
contents = contents.replace(fakeNameRegExp, require);
await fs.promises.writeFile(outfile, contents);
});
},
Expand Down