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

feat(bundler): inlining/dead-code-elimination for import.meta.main (and --compile) #12867

Merged
merged 51 commits into from
Aug 2, 2024

Conversation

paperdave
Copy link
Member

@paperdave paperdave commented Jul 27, 2024

What does this PR do?

Fixes #6009
Fixes #9366

  1. The value for import.meta.main is inlined to be true for bundler entry-points.
export function run() {
  console.log("running");
}

if (import.meta.main) {
  run();
}
  1. The expression require.main == module is now special cased to not not mark a module as CommonJS. This allows it to participate in the inlining.
import "fs";

if (typeof require !== "undefined" && require.main === module) {
  console.log("y u do dis");
}

Both of the above also support future --format=cjs (needed for js runtime that uses real commonjs modules) where import.meta.main when not known at bundle-time will emit require.main == module (one equal because it is shorter). Inverting this condition will correctly print require.main != module

  1. Support import.meta.main in --target=node

Node.js does not support import.meta.main, so this rewrites both forms into something that will actually work at runtime, as previously neither would.

console.log(import.meta.main);
console.log(require.main == module);

Will bundle to

import {createRequire} from "node:module";
var __require = createRequire(import.meta.url);

// import_meta_main.ts
console.log(__require.main == __require.module);
console.log(__require.main == __require.module);

TODO: This needs a two at-runtime tests, one for commonjs, one for esm. then one file for for true and false

paperdave and others added 30 commits July 25, 2024 22:48
Co-authored-by: dylan-conway <[email protected]>
@robobun
Copy link

robobun commented Jul 29, 2024

@paperdave, your commit 822428e has 20 failures in #1103

@paperdave paperdave marked this pull request as ready for review July 30, 2024 02:33
@Jarred-Sumner Jarred-Sumner merged commit 622432e into main Aug 2, 2024
45 checks passed
@Jarred-Sumner Jarred-Sumner deleted the dave/compile-import-meta-main branch August 2, 2024 00:25
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

Successfully merging this pull request may close these issues.

Make require.main === module an AST node Set import.meta.main for compiled executables
7 participants