From cf0ba8e951dda9cd261c9e904d52bc2d17167851 Mon Sep 17 00:00:00 2001 From: Tanishka Date: Wed, 17 Jul 2024 00:57:01 +0530 Subject: [PATCH 1/2] doc: update for solution to dual package hazard --- doc/api/packages.md | 321 +++++++++++++++----------------------------- 1 file changed, 107 insertions(+), 214 deletions(-) diff --git a/doc/api/packages.md b/doc/api/packages.md index 4316420620a224..3149ff4ee5184f 100644 --- a/doc/api/packages.md +++ b/doc/api/packages.md @@ -61,12 +61,12 @@ Node.js will treat the following as [ES modules][] when passed to `node` as the initial input, or when referenced by `import` statements or `import()` expressions: -* Files with an `.mjs` extension. +- Files with an `.mjs` extension. -* Files with a `.js` extension when the nearest parent `package.json` file +- Files with a `.js` extension when the nearest parent `package.json` file contains a top-level [`"type"`][] field with a value of `"module"`. -* Strings passed in as an argument to `--eval`, or piped to `node` via `STDIN`, +- Strings passed in as an argument to `--eval`, or piped to `node` via `STDIN`, with the flag `--input-type=module`. * Code containing syntax only successfully parsed as [ES modules][], such as @@ -82,28 +82,28 @@ Node.js will treat the following as [CommonJS][] when passed to `node` as the initial input, or when referenced by `import` statements or `import()` expressions: -* Files with a `.cjs` extension. +- Files with a `.cjs` extension. -* Files with a `.js` extension when the nearest parent `package.json` file +- Files with a `.js` extension when the nearest parent `package.json` file contains a top-level field [`"type"`][] with a value of `"commonjs"`. -* Strings passed in as an argument to `--eval` or `--print`, or piped to `node` +- Strings passed in as an argument to `--eval` or `--print`, or piped to `node` via `STDIN`, with the flag `--input-type=commonjs`. Aside from these explicit cases, there are other cases where Node.js defaults to one module system or the other based on the value of the [`--experimental-default-type`][] flag: -* Files ending in `.js` or with no extension, if there is no `package.json` file +- Files ending in `.js` or with no extension, if there is no `package.json` file present in the same folder or any parent folder. -* Files ending in `.js` or with no extension, if the nearest parent +- Files ending in `.js` or with no extension, if the nearest parent `package.json` field lacks a `"type"` field; unless the folder is inside a `node_modules` folder. (Package scopes under `node_modules` are always treated as CommonJS when the `package.json` file lacks a `"type"` field, regardless of `--experimental-default-type`, for backward compatibility.) -* Strings passed in as an argument to `--eval` or piped to `node` via `STDIN`, +- Strings passed in as an argument to `--eval` or piped to `node` via `STDIN`, when `--input-type` is unspecified. This flag currently defaults to `"commonjs"`, but it may change in the future to @@ -159,19 +159,19 @@ Node.js has two systems for resolving a specifier and loading modules. There is the CommonJS module loader: -* It is fully synchronous. -* It is responsible for handling `require()` calls. -* It is monkey patchable. -* It supports [folders as modules][]. -* When resolving a specifier, if no exact match is found, it will try to add +- It is fully synchronous. +- It is responsible for handling `require()` calls. +- It is monkey patchable. +- It supports [folders as modules][]. +- When resolving a specifier, if no exact match is found, it will try to add extensions (`.js`, `.json`, and finally `.node`) and then attempt to resolve [folders as modules][]. -* It treats `.json` as JSON text files. -* `.node` files are interpreted as compiled addon modules loaded with +- It treats `.json` as JSON text files. +- `.node` files are interpreted as compiled addon modules loaded with `process.dlopen()`. -* It treats all files that lack `.json` or `.node` extensions as JavaScript +- It treats all files that lack `.json` or `.node` extensions as JavaScript text files. -* It can only be used to [load ECMASCript modules from CommonJS modules][] if +- It can only be used to [load ECMASCript modules from CommonJS modules][] if the module graph is synchronous (that contains no top-level `await`) when `--experimental-require-module` is enabled. When used to load a JavaScript text file that is not an ECMAScript module, @@ -179,17 +179,17 @@ There is the CommonJS module loader: There is the ECMAScript module loader: -* It is asynchronous, unless it's being used to load modules for `require()`. -* It is responsible for handling `import` statements and `import()` expressions. -* It is not monkey patchable, can be customized using [loader hooks][]. -* It does not support folders as modules, directory indexes (e.g. +- It is asynchronous, unless it's being used to load modules for `require()`. +- It is responsible for handling `import` statements and `import()` expressions. +- It is not monkey patchable, can be customized using [loader hooks][]. +- It does not support folders as modules, directory indexes (e.g. `'./startup/index.js'`) must be fully specified. -* It does no extension searching. A file extension must be provided +- It does no extension searching. A file extension must be provided when the specifier is a relative or absolute file URL. -* It can load JSON modules, but an import type attribute is required. -* It accepts only `.js`, `.mjs`, and `.cjs` extensions for JavaScript text +- It can load JSON modules, but an import type attribute is required. +- It accepts only `.js`, `.mjs`, and `.cjs` extensions for JavaScript text files. -* It can be used to load JavaScript CommonJS modules. Such modules +- It can be used to load JavaScript CommonJS modules. Such modules are passed through the `cjs-module-lexer` to try to identify named exports, which are available if they can be determined through static analysis. Imported CommonJS modules have their URLs converted to absolute @@ -241,12 +241,12 @@ import 'commonjs-package/src/index.mjs'; The `.mjs` and `.cjs` extensions can be used to mix types within the same package: -* Within a `"type": "module"` package, Node.js can be instructed to +- Within a `"type": "module"` package, Node.js can be instructed to interpret a particular file as [CommonJS][] by naming it with a `.cjs` extension (since both `.js` and `.mjs` files are treated as ES modules within a `"module"` package). -* Within a `"type": "commonjs"` package, Node.js can be instructed to +- Within a `"type": "commonjs"` package, Node.js can be instructed to interpret a particular file as an [ES module][] by naming it with an `.mjs` extension (since both `.js` and `.cjs` files are treated as CommonJS within a `"commonjs"` package). @@ -647,25 +647,25 @@ For example, a package that wants to provide different ES module exports for Node.js implements the following conditions, listed in order from most specific to least specific as conditions should be defined: -* `"node-addons"` - similar to `"node"` and matches for any Node.js environment. +- `"node-addons"` - similar to `"node"` and matches for any Node.js environment. This condition can be used to provide an entry point which uses native C++ addons as opposed to an entry point which is more universal and doesn't rely on native addons. This condition can be disabled via the [`--no-addons` flag][]. -* `"node"` - matches for any Node.js environment. Can be a CommonJS or ES +- `"node"` - matches for any Node.js environment. Can be a CommonJS or ES module file. _In most cases explicitly calling out the Node.js platform is not necessary._ -* `"import"` - matches when the package is loaded via `import` or +- `"import"` - matches when the package is loaded via `import` or `import()`, or via any top-level import or resolve operation by the ECMAScript module loader. Applies regardless of the module format of the target file. _Always mutually exclusive with `"require"`._ -* `"require"` - matches when the package is loaded via `require()`. The +- `"require"` - matches when the package is loaded via `require()`. The referenced file should be loadable with `require()` although the condition matches regardless of the module format of the target file. Expected formats include CommonJS, JSON, native addons, and ES modules if `--experimental-require-module` is enabled. _Always mutually exclusive with `"import"`._ -* `"default"` - the generic fallback that always matches. Can be a CommonJS +- `"default"` - the generic fallback that always matches. Can be a CommonJS or ES module file. _This condition should always come last._ Within the [`"exports"`][] object, key order is significant. During condition @@ -766,14 +766,14 @@ Since custom package conditions require clear definitions to ensure correct usage, a list of common known package conditions and their strict definitions is provided below to assist with ecosystem coordination. -* `"types"` - can be used by typing systems to resolve the typing file for +- `"types"` - can be used by typing systems to resolve the typing file for the given export. _This condition should always be included first._ -* `"browser"` - any web browser environment. -* `"development"` - can be used to define a development-only environment +- `"browser"` - any web browser environment. +- `"development"` - can be used to define a development-only environment entry point, for example to provide additional debugging context such as better error messages when running in a development mode. _Must always be mutually exclusive with `"production"`._ -* `"production"` - can be used to define a production environment entry +- `"production"` - can be used to define a production environment entry point. _Must always be mutually exclusive with `"development"`._ For other runtimes, platform-specific condition key definitions are maintained @@ -783,16 +783,16 @@ New conditions definitions may be added to this list by creating a pull request to the [Node.js documentation for this section][]. The requirements for listing a new condition definition here are that: -* The definition should be clear and unambiguous for all implementers. -* The use case for why the condition is needed should be clearly justified. -* There should exist sufficient existing implementation usage. -* The condition name should not conflict with another condition definition or +- The definition should be clear and unambiguous for all implementers. +- The use case for why the condition is needed should be clearly justified. +- There should exist sufficient existing implementation usage. +- The condition name should not conflict with another condition definition or condition in wide usage. -* The listing of the condition definition should provide a coordination +- The listing of the condition definition should provide a coordination benefit to the ecosystem that wouldn't otherwise be possible. For example, this would not necessarily be the case for company-specific or application-specific conditions. -* The condition should be such that a Node.js user would expect it to be in +- The condition should be such that a Node.js user would expect it to be in Node.js core documentation. The `"types"` condition is a good example: It doesn't really belong in the [Runtime Keys][] proposal but is a good fit here in the Node.js docs. @@ -957,191 +957,84 @@ following conditions: browsers. 6. The hazards described in the previous section are avoided or minimized. -#### Approach #1: Use an ES module wrapper +#### Approach: Use Node/Default Conditions -Write the package in CommonJS or transpile ES module sources into CommonJS, and -create an ES module wrapper file that defines the named exports. Using -[Conditional exports][], the ES module wrapper is used for `import` and the -CommonJS entry point for `require`. +This approach leverages the node and default conditions in the exports field of package.json to provide the appropriate entry points based on the environment. + +1. Use the exports field in package.json to define separate entry points for Node.js and other environments. This ensures that Node.js always loads the CommonJS version, while other environments load the ES Module version. ```json -// ./node_modules/pkg/package.json +// package.json { - "type": "module", + "name": "your-package", + "version": "1.0.0", + "main": "./index.cjs", "exports": { - "import": "./wrapper.mjs", - "require": "./index.cjs" + "node": "./index.cjs", + "default": "./index.mjs" } } ``` -The preceding example uses explicit extensions `.mjs` and `.cjs`. -If your files use the `.js` extension, `"type": "module"` will cause such files -to be treated as ES modules, just as `"type": "commonjs"` would cause them -to be treated as CommonJS. -See [Enabling](esm.md#enabling). +2. Write your CommonJS entry point, which will be used by Node.js. ```cjs -// ./node_modules/pkg/index.cjs +// index.cjs exports.name = 'value'; ``` -```js -// ./node_modules/pkg/wrapper.mjs -import cjsModule from './index.cjs'; -export const name = cjsModule.name; +3. Write your ES Module entry point, which will be used by other environments like browsers. + +```mjs +// index.mjs +export const name = 'value'; ``` -In this example, the `name` from `import { name } from 'pkg'` is the same -singleton as the `name` from `const { name } = require('pkg')`. Therefore `===` -returns `true` when comparing the two `name`s and the divergent specifier hazard -is avoided. +4. Ensure that the module is stateless or properly isolates state to avoid issues when both the CommonJS and ES Module versions are used. -If the module is not simply a list of named exports, but rather contains a -unique function or object export like `module.exports = function () { ... }`, -or if support in the wrapper for the `import pkg from 'pkg'` pattern is desired, -then the wrapper would instead be written to export the default optionally -along with any named exports as well: +Stateless Module: +If your module does not maintain state, it can be safely used in both environments without additional considerations. + +Stateful Module: +If your module maintains state, ensure that the state is isolated or managed in a way that avoids conflicts between the CommonJS and ES Module versions. + +```cjs +// state.cjs +const state = { + value: 'some state', +}; +module.exports = state; +``` + +```mjs +// index.mjs +import state from './state.cjs'; +export { state }; +``` + +5. When your package is used in Node.js, it will automatically load the CommonJS version. ```js -import cjsModule from './index.cjs'; -export const name = cjsModule.name; -export default cjsModule; +const { name } = require('your-package'); +console.log(name); // Outputs: value ``` -This approach is appropriate for any of the following use cases: - -* The package is currently written in CommonJS and the author would prefer not - to refactor it into ES module syntax, but wishes to provide named exports for - ES module consumers. -* The package has other packages that depend on it, and the end user might - install both this package and those other packages. For example a `utilities` - package is used directly in an application, and a `utilities-plus` package - adds a few more functions to `utilities`. Because the wrapper exports - underlying CommonJS files, it doesn't matter if `utilities-plus` is written in - CommonJS or ES module syntax; it will work either way. -* The package stores internal state, and the package author would prefer not to - refactor the package to isolate its state management. See the next section. - -A variant of this approach not requiring conditional exports for consumers could -be to add an export, e.g. `"./module"`, to point to an all-ES module-syntax -version of the package. This could be used via `import 'pkg/module'` by users -who are certain that the CommonJS version will not be loaded anywhere in the -application, such as by dependencies; or if the CommonJS version can be loaded -but doesn't affect the ES module version (for example, because the package is -stateless): +6. When your package is used in ES Module environments like browsers, it will load the ES Module version. -```json -// ./node_modules/pkg/package.json -{ - "type": "module", - "exports": { - ".": "./index.cjs", - "./module": "./wrapper.mjs" - } -} +```js +import { name } from 'your-package'; +console.log(name); // Outputs: value ``` -#### Approach #2: Isolate state +#### Benefits of Using Node/Default Conditions -A [`package.json`][] file can define the separate CommonJS and ES module entry -points directly: +1. Node.js will always load the CommonJS version, avoiding the dual-package hazard. -```json -// ./node_modules/pkg/package.json -{ - "type": "module", - "exports": { - "import": "./index.mjs", - "require": "./index.cjs" - } -} -``` +2. Bundlers will load the appropriate version based on their configuration, ensuring that either the Node.js version or the default version is loaded, but not both. -This can be done if both the CommonJS and ES module versions of the package are -equivalent, for example because one is the transpiled output of the other; and -the package's management of state is carefully isolated (or the package is -stateless). - -The reason that state is an issue is because both the CommonJS and ES module -versions of the package might get used within an application; for example, the -user's application code could `import` the ES module version while a dependency -`require`s the CommonJS version. If that were to occur, two copies of the -package would be loaded in memory and therefore two separate states would be -present. This would likely cause hard-to-troubleshoot bugs. - -Aside from writing a stateless package (if JavaScript's `Math` were a package, -for example, it would be stateless as all of its methods are static), there are -some ways to isolate state so that it's shared between the potentially loaded -CommonJS and ES module instances of the package: - -1. If possible, contain all state within an instantiated object. JavaScript's - `Date`, for example, needs to be instantiated to contain state; if it were a - package, it would be used like this: - - ```js - import Date from 'date'; - const someDate = new Date(); - // someDate contains state; Date does not - ``` - - The `new` keyword isn't required; a package's function can return a new - object, or modify a passed-in object, to keep the state external to the - package. - -2. Isolate the state in one or more CommonJS files that are shared between the - CommonJS and ES module versions of the package. For example, if the CommonJS - and ES module entry points are `index.cjs` and `index.mjs`, respectively: - - ```cjs - // ./node_modules/pkg/index.cjs - const state = require('./state.cjs'); - module.exports.state = state; - ``` - - ```js - // ./node_modules/pkg/index.mjs - import state from './state.cjs'; - export { - state, - }; - ``` - - Even if `pkg` is used via both `require` and `import` in an application (for - example, via `import` in application code and via `require` by a dependency) - each reference of `pkg` will contain the same state; and modifying that - state from either module system will apply to both. - -Any plugins that attach to the package's singleton would need to separately -attach to both the CommonJS and ES module singletons. - -This approach is appropriate for any of the following use cases: - -* The package is currently written in ES module syntax and the package author - wants that version to be used wherever such syntax is supported. -* The package is stateless or its state can be isolated without too much - difficulty. -* The package is unlikely to have other public packages that depend on it, or if - it does, the package is stateless or has state that need not be shared between - dependencies or with the overall application. - -Even with isolated state, there is still the cost of possible extra code -execution between the CommonJS and ES module versions of a package. - -As with the previous approach, a variant of this approach not requiring -conditional exports for consumers could be to add an export, e.g. -`"./module"`, to point to an all-ES module-syntax version of the package: +3. This approach allows for an ES Module-only version to be used in environments that support ESM, leveraging the advantages of ESM syntax without risking the dual-package hazard. -```json -// ./node_modules/pkg/package.json -{ - "type": "module", - "exports": { - ".": "./index.cjs", - "./module": "./index.mjs" - } -} -``` +By following these steps and utilizing the node and default conditions, you can effectively write dual packages that avoid or minimize hazards, ensuring compatibility and proper functionality across different environments. ## Node.js `package.json` field definitions @@ -1151,17 +1044,17 @@ additional fields which are ignored by Node.js and not documented here. The following fields in `package.json` files are used in Node.js: -* [`"name"`][] - Relevant when using named imports within a package. Also used +- [`"name"`][] - Relevant when using named imports within a package. Also used by package managers as the name of the package. -* [`"main"`][] - The default module when loading the package, if exports is not +- [`"main"`][] - The default module when loading the package, if exports is not specified, and in versions of Node.js prior to the introduction of exports. -* [`"packageManager"`][] - The package manager recommended when contributing to +- [`"packageManager"`][] - The package manager recommended when contributing to the package. Leveraged by the [Corepack][] shims. -* [`"type"`][] - The package type determining whether to load `.js` files as +- [`"type"`][] - The package type determining whether to load `.js` files as CommonJS or ES modules. -* [`"exports"`][] - Package exports and conditional exports. When present, +- [`"exports"`][] - Package exports and conditional exports. When present, limits which submodules can be loaded from within the package. -* [`"imports"`][] - Package imports, for use by modules within the package +- [`"imports"`][] - Package imports, for use by modules within the package itself. ### `"name"` @@ -1178,7 +1071,7 @@ changes: description: Remove the `--experimental-resolve-self` option. --> -* Type: {string} +- Type: {string} ```json { @@ -1199,7 +1092,7 @@ The `"name"` field can be used in addition to the [`"exports"`][] field to added: v0.4.0 --> -* Type: {string} +- Type: {string} ```json { @@ -1208,7 +1101,7 @@ added: v0.4.0 ``` The `"main"` field defines the entry point of a package when imported by name -via a `node_modules` lookup. Its value is a path. +via a `node_modules` lookup. Its value is a path. When a package has an [`"exports"`][] field, this will take precedence over the `"main"` field when importing the package by name. @@ -1231,7 +1124,7 @@ added: > Stability: 1 - Experimental -* Type: {string} +- Type: {string} ```json { @@ -1260,7 +1153,7 @@ changes: description: Unflag `--experimental-modules`. --> -* Type: {string} +- Type: {string} The `"type"` field defines the module format that Node.js uses for all `.js` files that have that `package.json` file as their nearest parent. @@ -1271,7 +1164,7 @@ Files ending with `.js` are loaded as ES modules when the nearest parent The nearest parent `package.json` is defined as the first `package.json` found when searching in the current folder, that folder's parent, and so on up -until a node\_modules folder or the volume root is reached. +until a node_modules folder or the volume root is reached. ```json // package.json @@ -1333,7 +1226,7 @@ changes: description: Implement conditional exports. --> -* Type: {Object} | {string} | {string\[]} +- Type: {Object} | {string} | {string\[]} ```json { @@ -1362,7 +1255,7 @@ added: - v12.19.0 --> -* Type: {Object} +- Type: {Object} ```json // package.json From fedcd73f1a23e1d24512c94b8ea491667ccb07bd Mon Sep 17 00:00:00 2001 From: Tanishka Date: Wed, 31 Jul 2024 12:50:04 +0000 Subject: [PATCH 2/2] fix linter errors --- doc/api/packages.md | 112 ++++++++++++++++++++++---------------------- 1 file changed, 56 insertions(+), 56 deletions(-) diff --git a/doc/api/packages.md b/doc/api/packages.md index 3149ff4ee5184f..f71539a4dcea3c 100644 --- a/doc/api/packages.md +++ b/doc/api/packages.md @@ -61,12 +61,12 @@ Node.js will treat the following as [ES modules][] when passed to `node` as the initial input, or when referenced by `import` statements or `import()` expressions: -- Files with an `.mjs` extension. +* Files with an `.mjs` extension. -- Files with a `.js` extension when the nearest parent `package.json` file +* Files with a `.js` extension when the nearest parent `package.json` file contains a top-level [`"type"`][] field with a value of `"module"`. -- Strings passed in as an argument to `--eval`, or piped to `node` via `STDIN`, +* Strings passed in as an argument to `--eval`, or piped to `node` via `STDIN`, with the flag `--input-type=module`. * Code containing syntax only successfully parsed as [ES modules][], such as @@ -82,28 +82,28 @@ Node.js will treat the following as [CommonJS][] when passed to `node` as the initial input, or when referenced by `import` statements or `import()` expressions: -- Files with a `.cjs` extension. +* Files with a `.cjs` extension. -- Files with a `.js` extension when the nearest parent `package.json` file +* Files with a `.js` extension when the nearest parent `package.json` file contains a top-level field [`"type"`][] with a value of `"commonjs"`. -- Strings passed in as an argument to `--eval` or `--print`, or piped to `node` +* Strings passed in as an argument to `--eval` or `--print`, or piped to `node` via `STDIN`, with the flag `--input-type=commonjs`. Aside from these explicit cases, there are other cases where Node.js defaults to one module system or the other based on the value of the [`--experimental-default-type`][] flag: -- Files ending in `.js` or with no extension, if there is no `package.json` file +* Files ending in `.js` or with no extension, if there is no `package.json` file present in the same folder or any parent folder. -- Files ending in `.js` or with no extension, if the nearest parent +* Files ending in `.js` or with no extension, if the nearest parent `package.json` field lacks a `"type"` field; unless the folder is inside a `node_modules` folder. (Package scopes under `node_modules` are always treated as CommonJS when the `package.json` file lacks a `"type"` field, regardless of `--experimental-default-type`, for backward compatibility.) -- Strings passed in as an argument to `--eval` or piped to `node` via `STDIN`, +* Strings passed in as an argument to `--eval` or piped to `node` via `STDIN`, when `--input-type` is unspecified. This flag currently defaults to `"commonjs"`, but it may change in the future to @@ -159,19 +159,19 @@ Node.js has two systems for resolving a specifier and loading modules. There is the CommonJS module loader: -- It is fully synchronous. -- It is responsible for handling `require()` calls. -- It is monkey patchable. -- It supports [folders as modules][]. -- When resolving a specifier, if no exact match is found, it will try to add +* It is fully synchronous. +* It is responsible for handling `require()` calls. +* It is monkey patchable. +* It supports [folders as modules][]. +* When resolving a specifier, if no exact match is found, it will try to add extensions (`.js`, `.json`, and finally `.node`) and then attempt to resolve [folders as modules][]. -- It treats `.json` as JSON text files. -- `.node` files are interpreted as compiled addon modules loaded with +* It treats `.json` as JSON text files. +* `.node` files are interpreted as compiled addon modules loaded with `process.dlopen()`. -- It treats all files that lack `.json` or `.node` extensions as JavaScript +* It treats all files that lack `.json` or `.node` extensions as JavaScript text files. -- It can only be used to [load ECMASCript modules from CommonJS modules][] if +* It can only be used to [load ECMASCript modules from CommonJS modules][] if the module graph is synchronous (that contains no top-level `await`) when `--experimental-require-module` is enabled. When used to load a JavaScript text file that is not an ECMAScript module, @@ -179,17 +179,17 @@ There is the CommonJS module loader: There is the ECMAScript module loader: -- It is asynchronous, unless it's being used to load modules for `require()`. -- It is responsible for handling `import` statements and `import()` expressions. -- It is not monkey patchable, can be customized using [loader hooks][]. -- It does not support folders as modules, directory indexes (e.g. +* It is asynchronous, unless it's being used to load modules for `require()`. +* It is responsible for handling `import` statements and `import()` expressions. +* It is not monkey patchable, can be customized using [loader hooks][]. +* It does not support folders as modules, directory indexes (e.g. `'./startup/index.js'`) must be fully specified. -- It does no extension searching. A file extension must be provided +* It does no extension searching. A file extension must be provided when the specifier is a relative or absolute file URL. -- It can load JSON modules, but an import type attribute is required. -- It accepts only `.js`, `.mjs`, and `.cjs` extensions for JavaScript text +* It can load JSON modules, but an import type attribute is required. +* It accepts only `.js`, `.mjs`, and `.cjs` extensions for JavaScript text files. -- It can be used to load JavaScript CommonJS modules. Such modules +* It can be used to load JavaScript CommonJS modules. Such modules are passed through the `cjs-module-lexer` to try to identify named exports, which are available if they can be determined through static analysis. Imported CommonJS modules have their URLs converted to absolute @@ -241,12 +241,12 @@ import 'commonjs-package/src/index.mjs'; The `.mjs` and `.cjs` extensions can be used to mix types within the same package: -- Within a `"type": "module"` package, Node.js can be instructed to +* Within a `"type": "module"` package, Node.js can be instructed to interpret a particular file as [CommonJS][] by naming it with a `.cjs` extension (since both `.js` and `.mjs` files are treated as ES modules within a `"module"` package). -- Within a `"type": "commonjs"` package, Node.js can be instructed to +* Within a `"type": "commonjs"` package, Node.js can be instructed to interpret a particular file as an [ES module][] by naming it with an `.mjs` extension (since both `.js` and `.cjs` files are treated as CommonJS within a `"commonjs"` package). @@ -647,25 +647,25 @@ For example, a package that wants to provide different ES module exports for Node.js implements the following conditions, listed in order from most specific to least specific as conditions should be defined: -- `"node-addons"` - similar to `"node"` and matches for any Node.js environment. +* `"node-addons"` - similar to `"node"` and matches for any Node.js environment. This condition can be used to provide an entry point which uses native C++ addons as opposed to an entry point which is more universal and doesn't rely on native addons. This condition can be disabled via the [`--no-addons` flag][]. -- `"node"` - matches for any Node.js environment. Can be a CommonJS or ES +* `"node"` - matches for any Node.js environment. Can be a CommonJS or ES module file. _In most cases explicitly calling out the Node.js platform is not necessary._ -- `"import"` - matches when the package is loaded via `import` or +* `"import"` - matches when the package is loaded via `import` or `import()`, or via any top-level import or resolve operation by the ECMAScript module loader. Applies regardless of the module format of the target file. _Always mutually exclusive with `"require"`._ -- `"require"` - matches when the package is loaded via `require()`. The +* `"require"` - matches when the package is loaded via `require()`. The referenced file should be loadable with `require()` although the condition matches regardless of the module format of the target file. Expected formats include CommonJS, JSON, native addons, and ES modules if `--experimental-require-module` is enabled. _Always mutually exclusive with `"import"`._ -- `"default"` - the generic fallback that always matches. Can be a CommonJS +* `"default"` - the generic fallback that always matches. Can be a CommonJS or ES module file. _This condition should always come last._ Within the [`"exports"`][] object, key order is significant. During condition @@ -766,14 +766,14 @@ Since custom package conditions require clear definitions to ensure correct usage, a list of common known package conditions and their strict definitions is provided below to assist with ecosystem coordination. -- `"types"` - can be used by typing systems to resolve the typing file for +* `"types"` - can be used by typing systems to resolve the typing file for the given export. _This condition should always be included first._ -- `"browser"` - any web browser environment. -- `"development"` - can be used to define a development-only environment +* `"browser"` - any web browser environment. +* `"development"` - can be used to define a development-only environment entry point, for example to provide additional debugging context such as better error messages when running in a development mode. _Must always be mutually exclusive with `"production"`._ -- `"production"` - can be used to define a production environment entry +* `"production"` - can be used to define a production environment entry point. _Must always be mutually exclusive with `"development"`._ For other runtimes, platform-specific condition key definitions are maintained @@ -783,16 +783,16 @@ New conditions definitions may be added to this list by creating a pull request to the [Node.js documentation for this section][]. The requirements for listing a new condition definition here are that: -- The definition should be clear and unambiguous for all implementers. -- The use case for why the condition is needed should be clearly justified. -- There should exist sufficient existing implementation usage. -- The condition name should not conflict with another condition definition or +* The definition should be clear and unambiguous for all implementers. +* The use case for why the condition is needed should be clearly justified. +* There should exist sufficient existing implementation usage. +* The condition name should not conflict with another condition definition or condition in wide usage. -- The listing of the condition definition should provide a coordination +* The listing of the condition definition should provide a coordination benefit to the ecosystem that wouldn't otherwise be possible. For example, this would not necessarily be the case for company-specific or application-specific conditions. -- The condition should be such that a Node.js user would expect it to be in +* The condition should be such that a Node.js user would expect it to be in Node.js core documentation. The `"types"` condition is a good example: It doesn't really belong in the [Runtime Keys][] proposal but is a good fit here in the Node.js docs. @@ -1044,17 +1044,17 @@ additional fields which are ignored by Node.js and not documented here. The following fields in `package.json` files are used in Node.js: -- [`"name"`][] - Relevant when using named imports within a package. Also used +* [`"name"`][] - Relevant when using named imports within a package. Also used by package managers as the name of the package. -- [`"main"`][] - The default module when loading the package, if exports is not +* [`"main"`][] - The default module when loading the package, if exports is not specified, and in versions of Node.js prior to the introduction of exports. -- [`"packageManager"`][] - The package manager recommended when contributing to +* [`"packageManager"`][] - The package manager recommended when contributing to the package. Leveraged by the [Corepack][] shims. -- [`"type"`][] - The package type determining whether to load `.js` files as +* [`"type"`][] - The package type determining whether to load `.js` files as CommonJS or ES modules. -- [`"exports"`][] - Package exports and conditional exports. When present, +* [`"exports"`][] - Package exports and conditional exports. When present, limits which submodules can be loaded from within the package. -- [`"imports"`][] - Package imports, for use by modules within the package +* [`"imports"`][] - Package imports, for use by modules within the package itself. ### `"name"` @@ -1071,7 +1071,7 @@ changes: description: Remove the `--experimental-resolve-self` option. --> -- Type: {string} +* Type: {string} ```json { @@ -1092,7 +1092,7 @@ The `"name"` field can be used in addition to the [`"exports"`][] field to added: v0.4.0 --> -- Type: {string} +* Type: {string} ```json { @@ -1124,7 +1124,7 @@ added: > Stability: 1 - Experimental -- Type: {string} +* Type: {string} ```json { @@ -1153,7 +1153,7 @@ changes: description: Unflag `--experimental-modules`. --> -- Type: {string} +* Type: {string} The `"type"` field defines the module format that Node.js uses for all `.js` files that have that `package.json` file as their nearest parent. @@ -1164,7 +1164,7 @@ Files ending with `.js` are loaded as ES modules when the nearest parent The nearest parent `package.json` is defined as the first `package.json` found when searching in the current folder, that folder's parent, and so on up -until a node_modules folder or the volume root is reached. +until a node\_modules folder or the volume root is reached. ```json // package.json @@ -1226,7 +1226,7 @@ changes: description: Implement conditional exports. --> -- Type: {Object} | {string} | {string\[]} +* Type: {Object} | {string} | {string\[]} ```json { @@ -1255,7 +1255,7 @@ added: - v12.19.0 --> -- Type: {Object} +* Type: {Object} ```json // package.json