Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
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
79 changes: 67 additions & 12 deletions src/js_parser/p.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6146,26 +6146,81 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O
}),
};
}
// Node.js does not have import.meta.main, so we end up lowering
// this to `require.main === module`, but with the ESM format,
// both `require` and `module` are not present, so the code
// generation we need is:
//
// import { createRequire } from "node:module";
// var __require = createRequire(import.meta.url);
// var import_meta_main = __require.main === __require.module;
//
// The printer can handle this for us, but we need to reference
// a handle to the `__require` function.
if self.options.lower_import_meta_main_for_node_js {
self.record_usage_of_runtime_require();
return self.lower_import_meta_main_for_node_js(inverted, loc);
}
Expr {
loc,
data: js_ast::ExprData::EImportMetaMain(E::ImportMetaMain { inverted }),
}
}

fn lower_import_meta_main_for_node_js(&mut self, inverted: bool, loc: bun_ast::Loc) -> Expr {
// Outside of the CommonJS format the printer writes `require` as
// `__require`, so we need to reference a handle to that function.
Comment thread
robobun marked this conversation as resolved.
Resolved
self.record_usage_of_runtime_require();

if self.options.output_format != options::Format::Esm {
// The printer writes this as `require.main == module`.
return Expr {
loc,
data: js_ast::ExprData::EImportMetaMain(E::ImportMetaMain { inverted }),
Comment thread
robobun marked this conversation as resolved.
Resolved
};
}

// Node.js has import.meta.main since v22.18.0 and v24.2.0. Before that,
// the closest thing is `require.main === module`, but with the ESM
// format, both `require` and `module` are not present, and
Comment thread
robobun marked this conversation as resolved.
Resolved
// `require.main` is undefined when the entry point is an ES module.
// So that form is only the fallback, and the code generation we need is:
//
// import { createRequire } from "node:module";
// var __require = createRequire(import.meta.url);
// var import_meta_main = import.meta.main ?? __require.main == __require.module;
Comment thread
robobun marked this conversation as resolved.
Resolved
let require_module = self.new_expr(
E::Dot {
target: self.value_for_require(loc),
name: b"module".into(),
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
name_loc: loc,
..Default::default()
},
loc,
);
let require_main_is_module = self.new_expr(
E::Binary {
op: js_ast::op::Code::BinLooseEq,
left: Expr {
loc,
data: js_ast::ExprData::ERequireMain,
},
right: require_module,
},
loc,
);
let value = self.new_expr(
E::Binary {
op: js_ast::op::Code::BinNullishCoalescing,
left: Expr {
loc,
data: js_ast::ExprData::EImportMetaMain(E::ImportMetaMain { inverted: false }),
},
right: require_main_is_module,
},
loc,
);
if !inverted {
return value;
}
self.new_expr(
E::Unary {
op: js_ast::op::Code::UnNot,
value,
flags: E::UnaryFlags::default(),
},
loc,
)
}

pub(crate) fn keep_expr_symbol_name(&mut self, _value: Expr, _name: &[u8]) -> Expr {
_value
}
Expand Down
5 changes: 1 addition & 4 deletions src/js_printer/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3324,10 +3324,7 @@ pub(crate) mod __gated_printer {
}
}
ExprData::EImportMetaMain(data) => {
if self.options.module_type == bundle_opts::Format::Esm
&& self.options.target != bun_ast::Target::Node
{
// Node.js doesn't support import.meta.main
if self.options.module_type == bundle_opts::Format::Esm {
Comment thread
robobun marked this conversation as resolved.
Resolved
// Most of the time, leave it in there
if data.inverted {
self.add_source_mapping(expr.loc);
Expand Down
147 changes: 143 additions & 4 deletions test/bundler/bundler_edgecase.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2308,13 +2308,139 @@ describe("bundler", () => {
`,
},
target: "node",
capture: ["false", "false", "__require.main == __require.module", "__require.main == __require.module"],
capture: [
"false",
"false",
"import.meta.main ?? __require.main == __require.module",
"import.meta.main ?? __require.main == __require.module",
],
onAfterBundle(api) {
// This should not be marked as a CommonJS module
api.expectFile("/out.js").not.toMatch(/\brequire\b/); // __require is ok
api.expectFile("/out.js").not.toMatch(/[^\.:]module/); // `.module` and `node:module` are ok.
},
});
// Node.js runs the output as the entry point, then as a module that the entry point loads.
for (const format of ["esm", "cjs"] as const) {
const ext = format === "esm" ? "mjs" : "cjs";
for (const minify of [false, true]) {
itBundled(`edgecase/ImportMetaMainTargetNodeImported+${format}${minify ? "+minify" : ""}`, {
files: {
"/entry.ts": /* js */ `
console.log(JSON.stringify([import.meta.main, require.main === module, require.main !== module]));
`,
},
runtimeFiles: {
[`/importer.${ext}`]: format === "esm" ? `import "./out.mjs";` : `require("./out.cjs");`,
},
outfile: `/out.${ext}`,
target: "node",
format,
minifySyntax: minify,
minifyWhitespace: minify,
run: [
{ runtime: "node", stdout: "[true,true,false]" },
{ runtime: "node", file: `/importer.${ext}`, stdout: "[false,false,true]" },
Comment thread
robobun marked this conversation as resolved.
Resolved
],
});
}
}
// `import.meta.main ?? ...` needs parentheses next to most operators. "/old-node.mjs" runs the
// output with an `import.meta` that has no `main`, like Node.js before v22.18.0 and v24.2.0.
for (const minify of [false, true]) {
itBundled(`edgecase/ImportMetaMainTargetNodePrecedence${minify ? "+minify" : ""}`, {
files: {
"/entry.ts": /* js */ `
console.log(JSON.stringify([
!import.meta.main,
typeof import.meta.main,
import.meta.main.toString(),
(require.main !== module).toString(),
(require.main !== module) ** 2,
import.meta.main ? "entry" : "imported",
import.meta.main || "imported",
import.meta.main && "entry",
import.meta.main ?? "unreachable",
"is entry: " + import.meta.main,
"main" in import.meta,
]));
`,
},
runtimeFiles: {
"/importer.mjs": `import "./out.mjs";`,
"/old-node.mjs": /* js */ `
import { readFileSync } from "node:fs";
import * as nodeModule from "node:module";
import { SourceTextModule, SyntheticModule } from "node:vm";

const url = new URL("./out.mjs", import.meta.url);
const output = new SourceTextModule(readFileSync(url, "utf8"), {
identifier: url.href,
initializeImportMeta(meta) {
meta.url = url.href;
},
});
await output.link(
() =>
new SyntheticModule(Object.keys(nodeModule), function () {
for (const name of Object.keys(nodeModule)) this.setExport(name, nodeModule[name]);
}),
);
await output.evaluate();
`,
},
outfile: "/out.mjs",
target: "node",
format: "esm",
minifySyntax: minify,
minifyWhitespace: minify,
run: [
{
runtime: "node",
stdout: `[false,"boolean","true","false",0,"entry",true,"entry",true,"is entry: true",true]`,
},
{
runtime: "node",
file: "/importer.mjs",
stdout: `[true,"boolean","false","true",1,"imported","imported",false,false,"is entry: false",true]`,
},
{
runtime: "node",
bunArgs: ["--experimental-vm-modules"],
file: "/old-node.mjs",
stdout: `[false,"boolean","true","false",0,"entry",true,"entry",true,"is entry: true",false]`,
},
],
});
}
// With --splitting, another entry point imports "/lib.ts", so its module is in a shared chunk.
itBundled("edgecase/ImportMetaMainTargetNodeSplitting", {
files: {
"/cli.ts": /* js */ `
import { libIsMain } from "./lib";
console.log(JSON.stringify({ cli: import.meta.main, lib: libIsMain }));
`,
"/lib.ts": /* js */ `
export const libIsMain = import.meta.main;
`,
},
entryPoints: ["/cli.ts", "/lib.ts"],
splitting: true,
outdir: "/out",
target: "node",
format: "esm",
run: { runtime: "node", file: "/out/cli.js", stdout: `{"cli":true,"lib":false}` },
});
// A "#!/usr/bin/env bun" entry point is parsed for bun, which has no `__require`.
itBundled("edgecase/ImportMetaMainTargetNodeBunShebang", {
files: {
"/entry.ts": `#!/usr/bin/env bun
console.log(import.meta.main, require.main === module);`,
},
target: "node",
format: "esm",
run: { stdout: "true true" },
});
itBundled("edgecase/build-cjs-module#20308", {
files: {
"/entry.ts": /* js */ `
Expand Down Expand Up @@ -3800,9 +3926,9 @@ describe("bundler", () => {
},
run: { stdout: "true" },
});
// `import.meta.main` is rewritten to EImportMetaMain; under `target: node`
// that prints as `__require.main == __require.module` without its own paren
// wrap, so an unwrapped `delete` would bind to `__require.main`.
// `import.meta.main` is rewritten to EImportMetaMain; in CommonJS output
// that prints as `require.main == module` without its own paren wrap, so an
// unwrapped `delete` would bind to `require.main`.
itBundled("edgecase/DeleteFoldedImportMetaMainRef", {
files: {
"/entry.js": /* js */ `
Expand All @@ -3826,6 +3952,19 @@ describe("bundler", () => {
},
run: { runtime: "node", stdout: "true" },
});
itBundled("edgecase/DeleteFoldedImportMetaMainRefNodeCjs", {
files: {
"/entry.js": /* js */ `
console.log(delete (null ?? import.meta.main));
`,
},
target: "node",
format: "cjs",
onAfterBundle: api => {
expect(api.readFile("out.js")).not.toMatch(/delete\s+require\.main\b/);
},
run: { runtime: "node", stdout: "true" },
});
// A same-file `const enum` member is inlined to an EInlinedEnum wrapping an
// ENumber during the visit pass, so the NaN/Infinity check has to look
// through the wrapper.
Expand Down
18 changes: 18 additions & 0 deletions test/bundler/transpiler/transpiler.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -4968,6 +4968,24 @@ console.log(foo, array);
const result = await transpiler.transform(input);
expect(result).toBe(`let list = [\"\\u2022\", \"-\", \"\\u25E6\", \"\\u25AA\", \"\\u25AB\"];\n`);
});

// An ES module has no `require` or `module` in Node.js.
it("import.meta.main - node and browser targets", () => {
const input = `
export const a = import.meta.main;
export const b = !import.meta.main;
export const c = require.main === module;
export const d = require.main !== module;
`;
const output =
"export const a = import.meta.main;\n" +
"export const b = !import.meta.main;\n" +
"export const c = import.meta.main;\n" +
"export const d = !import.meta.main;\n";
for (const target of ["node", "browser"]) {
expect(new Bun.Transpiler({ loader: "ts", target }).transformSync(input)).toBe(output);
}
});
});

describe("edge cases", () => {
Expand Down
Loading