Skip to content

esm: implement import.meta.main #57804

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

Open
wants to merge 14 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
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
31 changes: 31 additions & 0 deletions doc/api/esm.md
Original file line number Diff line number Diff line change
Expand Up @@ -391,6 +391,32 @@ import { readFileSync } from 'node:fs';
const buffer = readFileSync(new URL('./data.proto', import.meta.url));
```

### `import.meta.main`

<!-- YAML
added:
- REPLACEME
-->

> Stability: 1.0 - Early development

* {boolean} `true` when the current module is the entry point of the current process; `false` otherwise.
* Equivalent to `require.main === module` in CommonJS.
* Analogous to Python's `__name__ == "__main__"`.

```js
export function foo() {
console.log('Hello, world!');
}

function main() {
foo();
}

if (import.meta.main) main();
// `foo` can be imported from another module without possible side-effects from `main`
```

### `import.meta.resolve(specifier)`

<!-- YAML
Expand Down Expand Up @@ -607,6 +633,10 @@ These CommonJS variables are not available in ES modules.
They can instead be loaded with [`module.createRequire()`][] or
[`process.dlopen`][].

#### No `require.main`

To replace `require.main === module`, there is the [`import.meta.main`][] API.

#### No `require.resolve`

Relative resolution can be handled via `new URL('./local', import.meta.url)`.
Expand Down Expand Up @@ -1167,6 +1197,7 @@ resolution for ESM specifiers is [commonjs-extension-resolution-loader][].
[`import()`]: #import-expressions
[`import.meta.dirname`]: #importmetadirname
[`import.meta.filename`]: #importmetafilename
[`import.meta.main`]: #importmetamain
[`import.meta.resolve`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import.meta/resolve
[`import.meta.url`]: #importmetaurl
[`import`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import
Expand Down
6 changes: 4 additions & 2 deletions lib/internal/modules/esm/initialize_import_meta.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,12 +49,12 @@ function createImportMetaResolve(defaultParentURL, loader, allowParentURL) {
/**
* Create the `import.meta` object for a module.
* @param {object} meta
* @param {{url: string}} context
* @param {{url: string, isMain?: boolean}} context
* @param {typeof import('./loader.js').ModuleLoader} loader Reference to the current module loader
* @returns {{dirname?: string, filename?: string, url: string, resolve?: Function}}
*/
function initializeImportMeta(meta, context, loader) {
const { url } = context;
const { url, isMain } = context;

// Alphabetical
if (StringPrototypeStartsWith(url, 'file:') === true) {
Expand All @@ -65,6 +65,8 @@ function initializeImportMeta(meta, context, loader) {
meta.filename = filePath;
}

meta.main = !!isMain;

if (!loader || loader.allowImportMetaResolve) {
meta.resolve = createImportMetaResolve(url, loader, experimentalImportMetaResolve);
}
Expand Down
3 changes: 2 additions & 1 deletion lib/internal/modules/esm/translators.js
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,8 @@ translators.set('module', function moduleStrategy(url, source, isMain) {
source = stringify(source);
debug(`Translating StandardModule ${url}`);
const { compileSourceTextModule } = require('internal/modules/esm/utils');
const module = compileSourceTextModule(url, source, this);
const context = isMain ? { isMain } : undefined;
const module = compileSourceTextModule(url, source, this, context);
return module;
});

Expand Down
11 changes: 9 additions & 2 deletions lib/internal/modules/esm/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ function registerModule(referrer, registry) {
*/
function defaultInitializeImportMetaForModule(meta, wrap) {
const cascadedLoader = require('internal/modules/esm/loader').getOrInitializeCascadedLoader();
return cascadedLoader.importMetaInitialize(meta, { url: wrap.url });
return cascadedLoader.importMetaInitialize(meta, { url: wrap.url, isMain: wrap.isMain });
}

/**
Expand Down Expand Up @@ -342,15 +342,22 @@ async function initializeHooks() {
* @param {string} source Source code of the module.
* @param {typeof import('./loader.js').ModuleLoader|undefined} cascadedLoader If provided,
* register the module for default handling.
* @param {{ isMain?: boolean }|undefined} context - context object containing module metadata.
* @returns {ModuleWrap}
*/
function compileSourceTextModule(url, source, cascadedLoader) {
function compileSourceTextModule(url, source, cascadedLoader, context = {}) {
const hostDefinedOption = cascadedLoader ? source_text_module_default_hdo : undefined;
const wrap = new ModuleWrap(url, undefined, source, 0, 0, hostDefinedOption);

if (!cascadedLoader) {
return wrap;
}

const { isMain } = context;
if (isMain) {
wrap.isMain = true;
}

// Cache the source map for the module if present.
if (wrap.sourceMapURL) {
maybeCacheSourceMap(url, source, wrap, false, undefined, wrap.sourceMapURL);
Expand Down
10 changes: 10 additions & 0 deletions test/es-module/test-esm-import-meta-main.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { mustCall } from '../common/index.mjs';
import assert from 'assert';

assert.strictEqual(import.meta.main, true);

import('../fixtures/es-modules/import-meta-main.mjs').then(
mustCall(({ isMain }) => {
assert.strictEqual(isMain, false);
})
);
2 changes: 1 addition & 1 deletion test/es-module/test-esm-import-meta.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import assert from 'assert';

assert.strictEqual(Object.getPrototypeOf(import.meta), null);

const keys = ['dirname', 'filename', 'resolve', 'url'];
const keys = ['dirname', 'filename', 'main', 'resolve', 'url'];
assert.deepStrictEqual(Reflect.ownKeys(import.meta), keys);

const descriptors = Object.getOwnPropertyDescriptors(import.meta);
Expand Down
1 change: 1 addition & 0 deletions test/fixtures/es-modules/import-meta-main.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const isMain = import.meta.main;
Loading