Skip to content

Commit c5a8636

Browse files
authored
Make esbuild require hack look better in output (#56060)
1 parent e1ef69d commit c5a8636

File tree

1 file changed

+8
-4
lines changed

1 file changed

+8
-4
lines changed

Herebyfile.mjs

+8-4
Original file line numberDiff line numberDiff line change
@@ -217,18 +217,22 @@ function createBundler(entrypoint, outfile, taskOptions = {}) {
217217
// to be consumable by other bundlers, we need to convert these calls back to
218218
// require so our imports are visible again.
219219
//
220-
// The leading spaces are to keep the offsets the same within the files to keep
221-
// source maps working (though this only really matters for the line the require is on).
220+
// To fix this, we redefine "require" to a name we're unlikely to use with the
221+
// same length as "require", then replace it back to "require" after bundling,
222+
// ensuring that source maps still work.
222223
//
223224
// See: https://github.com/evanw/esbuild/issues/1905
224-
options.define = { require: "$$require" };
225+
const require = "require";
226+
const fakeName = "Q".repeat(require.length);
227+
const fakeNameRegExp = new RegExp(fakeName, "g");
228+
options.define = { [require]: fakeName };
225229
options.plugins = [
226230
{
227231
name: "fix-require",
228232
setup: build => {
229233
build.onEnd(async () => {
230234
let contents = await fs.promises.readFile(outfile, "utf-8");
231-
contents = contents.replace(/\$\$require/g, " require");
235+
contents = contents.replace(fakeNameRegExp, require);
232236
await fs.promises.writeFile(outfile, contents);
233237
});
234238
},

0 commit comments

Comments
 (0)