Skip to content

Commit 2ac8377

Browse files
authored
feat: implement module type resolution algorithm ESM_FILE_FORMAT from the spec (#535)
resolves #527 fixes #508 This PR adds a new `module_type` option and also to the returned result. ```ts export interface NapiResolveOptions { /** * Resolve [ResolveResult::moduleType]. * * Default `false` */ moduleType?: boolean } ``` ```ts export interface ResolveResult { /** * Module type for this path. * * The module type is computed `ESM_FILE_FORMAT` from the [ESM resolution algorithm specification](https://nodejs.org/docs/latest/api/esm.html#resolution-algorithm-specification). * * The algorithm uses the file extension or finds the closest `package.json` with the `type` field. */ moduleType?: ModuleType } export declare const enum ModuleType { Module = 'module', CommonJs = 'commonjs', Json = 'json', Wasm = 'wasm', Addon = 'addon' } ``` Node.js will treat the following as [ES modules](https://nodejs.org/api/esm.html): * Files with an .mjs extension. * Files with a .js extension when the nearest parent package.json file contains a top-level ["type"](https://nodejs.org/api/packages.html#type) field with a value of "module". Node.js will treat the following as [CommonJS](https://nodejs.org/api/modules.html): * Files with a .cjs extension. * Files with a .js extension when the nearest parent package.json file contains a top-level field ["type"](https://nodejs.org/api/packages.html#type) with a value of "commonjs". See * https://nodejs.org/api/packages.html#determining-module-system * `ESM_FILE_FORMAT` in https://nodejs.org/docs/latest/api/esm.html#resolution-algorithm-specification
1 parent ff7bd35 commit 2ac8377

35 files changed

+289
-16
lines changed

examples/resolver.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ fn main() {
4343
Err(error) => println!("Error: {error}"),
4444
Ok(resolution) => {
4545
println!("Resolution: {}", resolution.full_path().to_string_lossy());
46+
println!("Module Type: {:?}", resolution.module_type());
4647
println!(
4748
"package json: {:?}",
4849
resolution.package_json().map(|p| p.path.to_string_lossy())

fixtures/misc/module-type/cjs/file.cjs

Whitespace-only changes.

fixtures/misc/module-type/cjs/file.js

Whitespace-only changes.

fixtures/misc/module-type/cjs/file.mjs

Whitespace-only changes.
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
{
2+
"type": "commonjs"
3+
}

fixtures/misc/module-type/esm/file.cjs

Whitespace-only changes.

fixtures/misc/module-type/esm/file.js

Whitespace-only changes.

fixtures/misc/module-type/esm/file.mjs

Whitespace-only changes.
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
{
2+
"type": "module"
3+
}

fixtures/misc/module-type/file

Whitespace-only changes.

0 commit comments

Comments
 (0)