API Reference
As ECMAScript module support grows, there are still several features missing from the Node.js ecosystem - some of which were available prior to the evolution of ESM.
mlly exposes several tools to bridge this gap.
CONDITIONS
Default export conditions.
const CONDITIONS: Set<string> = new Set(['node', 'import'])
See Also
EXTENSION_FORMAT_MAP
Default file extension to module formats map.
const EXTENSION_FORMAT_MAP: Map<Ext, Format> = new Map<Ext, Format>([
['.cjs', Format.COMMONJS],
['.cts', Format.COMMONJS],
['.d.cts', Format.COMMONJS],
['.d.mts', Format.MODULE],
['.d.ts', Format.MODULE],
['.js', Format.MODULE],
['.json', Format.JSON],
['.jsx', Format.MODULE],
['.mjs', Format.MODULE],
['.mts', Format.MODULE],
['.node', Format.COMMONJS],
['.ts', Format.MODULE],
['.tsx', Format.MODULE],
['.wasm', Format.WASM]
])
See Also
PATTERN_CHARACTER
Character representing a subpath pattern.
const PATTERN_CHARACTER: string = '*'
RESOLVE_EXTENSIONS
Default resolvable file extensions.
const RESOLVE_EXTENSIONS: Set<Ext> = new Set([
'.mjs',
'.mts',
'.cjs',
'.cts',
'.js',
'.ts',
'.jsx',
'.tsx',
'.css',
'.json',
'.node',
'.wasm',
'.d.mts',
'.d.cts',
'.d.ts'
])
See Also
compareSubpaths
Returns a number indicating if a subpath pattern is equal to, greater than, or less than another subpath pattern.
-1:subpath2is less thansubpath10:subpath2is equal tosubpath11:subpath2is greater thansubpath1
Implements the PATTERN_KEY_COMPARE algorithm.
See Also
Params
string |
subpath1 |
Subpath to be compared |
string |
subpath2 |
Subpath to compare subpath1 to |
Returns
CompareResult Comparsion result
THROWS NodeError<Error | TypeError>
If either either subpath contains more
than pattern character ('*') or is not a string
detectSyntax
Detects if code contains CommonJS syntax, ESM syntax, or a mixture of both.
Ignores matches in comments.
See Also
Params
string |
code |
Code to evaluate |
Returns
{ cjs: boolean; esm: boolean; mixed: boolean } Detection result
extractStatements
Finds all export, import, and/or require statements in code.
Ignores matches in comments.
See Also
Params
string |
[code=''] |
Code to evaluate |
Returns
Statement[] Extracted statements
THROWS NodeError<TypeError>
If code is not a string
fillModules
Ensures all absolute and relative module specifiers in the given piece of
source code are fully specified.
Ignores specifiers that already have file extensions.
See Also
FillModuleOptions- https://nodejs.org/api/esm.html#mandatory-file-extensions
- https://nodejs.org/api/esm.html#terminology
Params
string |
code |
Code to evaluate |
FillModuleOptions |
options |
Module fill options |
Returns
Promise<string> code with fully specified module specifiers
THROWS NodeError<TypeError>
findDynamicImports
Finds all dynamic import statements in code. Ignores matches in comments.
See Also
DynamicImport- https://regex101.com/r/PTPAvU
- https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/import
Params
string |
[code=''] |
Code to evaluate |
Returns
DynamicImport[] Dynamic import statement objects
THROWS NodeError<TypeError>
If code is not a string
findExports
Finds all export statements in code. Ignores matches in comments.
See Also
ExportStatement- https://regex101.com/r/JtvRUt
- https://regex101.com/r/8HpMrA
- https://regex101.com/r/G7GhEt
- https://regex101.com/r/KQEDdZ
- https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/export
Params
string |
[code=''] |
Code to evaluate |
Returns
ExportStatement[] Export statement objects
THROWS NodeError<TypeError>
If code is not a string
findRequires
Finds all require statements in code. Ignores matches in comments.
See Also
Params
string |
[code=''] |
Code to evaluate |
Returns
RequireStatement[] Require statement objects
THROWS NodeError<TypeError>
If code is not a string
findStaticImports
Finds all static import statements in code. Ignores matches in comments.
See Also
StaticImport- https://regex101.com/r/wlYQUN
- https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/import
Params
string |
[code=''] |
Code to evaluate |
Returns
StaticImport[] Static import statement objects
THROWS NodeError<TypeError>
If code is not a string
findSubpath
Finds the subpath defined in context, a package.json exports or
imports field, that maps to the given package target.
Supports extensionless targets and targets without explicit '/index' usage.
Returns null if a subpath is not found.
See Also
ExportsFindSubpathOptionsImports- https://nodejs.org/api/packages.html#subpath-exports
- https://nodejs.org/api/packages.html#subpath-imports
Params
string |
target |
Package target to find in context |
Nilable<Exports | Imports> |
context |
Package context |
FindSubpathOptions |
options |
Search options |
Returns
Nullable<string> Subpath defined in context or null
THROWS NodeError<Error | TypeError>
getFormat
Retrieves a module format for the given module id.
TIP
The given module id should be absolute (i.e. a file: URL or absolute
specifier).
See Also
Params
ModuleId |
id |
Module id to evaluate |
GetFormatOptions? |
[options={}] |
Format retrieval options |
Returns
Promise<Nilable<Format>> Module format, null, or undefined
THROWS NodeError<TypeError>
getSource
Retrieves source code for the given module id.
TIP
The given module id should be absolute (i.e. a file: URL or absolute
specifier).
See Also
GetSourceOptionsModuleId- https://nodejs.org/docs/latest-v19.x/api/esm.html#loadurl-context-nextload
Params
ModuleId |
id |
Module id to evaluate |
GetSourceOptions? |
[options={}] |
Source code retrieval options |
Returns
Promise<Optional<Uint8Array | string>> Source code for id
THROWS NodeError
If unsupported URL scheme is encountered
hasCJSSyntax
Detects if code contains CommonJS syntax. Ignores matches in comments.
Syntax patterns:
__dirname__filenameawait importexportsmodule.exportsrequirerequire.*
See Also
Params
string |
code |
Code to evaluate |
Returns
boolean true if code contains cjs syntax, false otherwise
THROWS NodeError<TypeError>
If code is not a string
hasESMSyntax
Detects if code contains ESM syntax. Ignores matches in comments.
Syntax patterns:
export(declaration, default, named, star)import(default, dynamic, named, star)import.meta.(env|resolve|url)
See Also
Params
string |
code |
Code to evaluate |
Returns
boolean true if code contains esm syntax, false otherwise
THROWS NodeError<TypeError>
If code is not a string
isAbsoluteSpecifier
Checks if the given specifier is an absolute specifier.
WARNING
Only checks specifier syntax. Does not guarantee the specifier references a file that exists.
See Also
Params
string |
specifier |
Specifier to evaluate |
Returns
boolean true if specifier is absolute specifier
THROWS NodeError<TypeError>
If specifier is not a string
isBareSpecifier
Checks if the given specifier is a bare specifier.
WARNING
Only checks specifier syntax. Does not guarantee the specifier references a file that exists.
See Also
Params
string |
specifier |
Specifier to evaluate |
Returns
boolean true if specifier is bare specifier
THROWS NodeError<TypeError>
If specifier is not a string
isDirectory
Checks if a directory exists at the given module id.
Params
ModuleId |
id |
Module id to evaluate |
Returns
boolean true if directory exists at id
isExportsSugar
Checks if the given package exports value is using exports sugar.
See Also
Params
Nilable<Exports> |
exports |
Package exports |
ModuleId |
pkg |
URL of relevant package.json file |
ModuleId |
parent |
URL of module to resolve from |
Returns
boolean true if exports is using exports sugar
isFile
Checks if a file exists at the given module id.
Params
ModuleId |
id |
Module id to evaluate |
Returns
boolean true if file exists at id
isRelativeSpecifier
Checks if the given specifier is a relative specifier.
WARNING
Only checks specifier syntax. Does not guarantee the specifier references a file that exists.
See Also
Params
string |
specifier |
Specifier to evaluate |
Returns
boolean true if specifier is relative specifier
lookupPackageScope
Finds a package.json file for the given module id. Ends the search at the
given end point after checking for a package.json file.
Returns null if a package.json file is not found.
See Also
Params
ModuleId |
id |
Id of module to get package scope for |
ModuleId? |
[stopdir=pathe.sep] |
Directory to end search |
string? |
[specifier] |
Module specifier passed by user |
ModuleId? |
[parent] |
Id of module to resolve from |
Returns
?PackageScope Package scope result or null
parseDataURL
Parses a data: URL.
If valid, returns an object representing the given url.
Note: A MIME type string is required.
See Also
Params
URL | string |
url |
URL to evaluate |
Returns
ParsedDataUrl Object representing url
parseModuleId
Creates an object representation the given module id.
See Also
Params
ModuleId |
id |
Module id to parse |
ParseModuleIdOptions? |
[options={}] |
Parsing options |
Returns
ParsedModuleId Object representing id
THROWS NodeError<TypeError>
parseSubpath
Creates an object representation of a subpath export or import from the given
module specifier after ensuring the subpath defined in specifier is also
defined in the given package context, a package.json exports or
imports field.
WARNING
Does not guarantee specifier resolves to an existing module.
See Also
ExportsImportsParseSubpathOptionsParsedSubpath- https://nodejs.org/api/packages.html#subpath-exports
- https://nodejs.org/api/packages.html#subpath-imports
Params
string |
specifier |
Module specifier to evaluate |
Optional<Exports | Imports> |
context |
Package context |
ParseSubpathOptions |
options |
Parsing options |
Returns
ParsedSubpath Object representing package subpath
THROWS NodeError<Error | TypeError>
readPackageJson
Reads a package.json file from the given directory.
Returns null if a file is not found.
See Also
Params
ModuleId |
[dir='.'] |
Id of directory containing package.json file |
string? |
[specifier] |
Module specifier passed by user to initiate |
ModuleId? |
[parent] |
Id of module to resolve from |
Returns
?PackageJson package.json object or null if file is not found
resolveAlias
Resolves a path alias in the given module specifier; does nothing if a path
match isn't found.
See Also
Params
string |
specifier |
Module specifier to evaluate |
ResolveAliasOptions |
[options={}] |
Resolution options |
Returns
Promise<string> Resolved specifier or original module specifier
THROWS NodeError
resolveAliases
Resolves path aliases in the given piece of source code.
See Also
Params
string |
code |
Code to evaluate |
ResolveAliasOptions |
[options={}] |
Resolve alias options |
Returns
Promise<string> code unmodified or with path aliases resolved
resolveModule
Resolves specifier according to the ESM Resolver algorithm, mostly 😉.
Adds support for:
- Extensionless file and directory index resolution
- Replacing file extensions
Other differences between Node.js:
- Subpath import targets (that are strings) must be relative to the
current working directory (e.g.
'./src/index.ts','./src/*.ts') or start with a valid NPM package name. Seenodejs/node#40579for details.
See Also
Params
string |
specifier |
Module specifier to resolve |
ResolveModuleOptions |
[options={}] |
Module resolution options |
Returns
Promise<URL> Resolved module URL
THROWS NodeError
resolveModules
Converts all module specifiers in code to absolute specifiers.
INFO
Useful for converting code to data: URLs.
See Also
Params
string |
code |
Code to evaluate |
ResolveModuleOptions |
[options={}] |
Module resolution options |
Returns
Promise<string> code with module specifiers fully resolved
toAbsoluteSpecifier
Converts specifier into an absolute specifier.
INFO
The absolute specifier will only include a file extension if specifier
includes a file extension.
See Also
Params
ModuleId |
specifier |
Module specifier to convert |
ModuleId |
[cwd=pathToFileURL('./')] |
Current working directory |
Returns
string specifier as absolute specifier (file url)
toBareSpecifier
Converts the given module specifier into a bare specifier.
The new specifier is not guaranteed to resolve to an existing module, nor
is it guaranteed to have a file extension, but it is guaranteed to be a
package path containing a valid subpath export if the specifier's parent
package uses package exports. If the parent package does not use
exports, the new specifier is only guaranteed to begin with a valid NPM
package name or Node.js builtin module name.
The given module specifier should be absolute, syntactically bare (i.e. not
begin with '/' or '.'), or relative to the current working directory
(e.g. './dist/index.mjs').
WARNING
Internal specifier (i.e. subpath import; '#src', '#src/utils')
conversion is not supported. Converting to an internal specifier will be
supported in the future.
See Also
Params
ModuleId |
specifier |
Module specifier to convert |
ModuleId |
parent |
URL of module to resolve from |
Set<string>? |
[conditions=CONDITIONS] |
Export conditions |
Returns
string specifier as bare specifier
THROWS NodeError
toDataURL
Converts code into a data: URL using base64 encoding.
TIP
data: URLs only resolve bare specifiers for builtin modules and
absolute specifiers.
Call await resolveModules(code) to ensure all specifiers are absolute
or bare.
See Also
Params
string |
code |
Code to convert |
MimeType |
[mime='text/javascript'] |
MIME type |
Returns
string code as data: URL
THROWS NodeError<TypeError>
If code or mime is not a string
toNodeURL
Converts the given module specifier to a node: URL.
WARNING
Does not guarantee the new specifier is an existing Node.js builtin module.
See Also
Params
string |
specifier |
Module specifier to convert |
Returns
string specifier as node: URL
THROWS NodeError<TypeError>
If specifier is not a string
toRelativeSpecifier
Converts specifier into a relative specifier.
INFO
The relative specifier will only include a file extension if specifier
includes a file extension.
See Also
Params
ModuleId |
specifier |
Module specifier to convert |
ModuleId |
parent |
Parent module URL or path to resolve from |
Returns
string specifier as relative specifier
toURL
Converts the given module id to an instance of URL.
See Also
Params
ModuleId |
id |
Module id to evaluate |
ModuleId? |
[base=pathToFileURL('./')] |
Base URL to resolve against |
Returns
URL id as instance of URL
validateAssertions
Test a module's import assertions.
See Also
Params
ModuleId |
url |
Module URL of imported module (for error reporting) |
LiteralUnion<Format, string> |
format |
Module format |
ImportAssertions |
[assertions={}] |
import assertions |
Returns
true true if assertions are valid
THROWS NodeError<TypeError>
validateExports
Validates the given package exports configuration and schema.
See Also
Params
Optional<Exports> |
exports |
Package exports |
ModuleId |
pkg |
URL of relevant package.json file |
ModuleId |
parent |
URL of module to resolve from |
Returns
true true if exports configuration and schema are valid