Rust port of enhanced-resolve, tsconfig-paths-webpack-plugin and tsconfck
- Released on crates.io and npm.
- Implements the ESM and CommonJS module resolution algorithm specification.
- Built-in tsconfig-paths-webpack-plugin
- support extending tsconfig defined in
tsconfig.extends - support paths alias defined in
tsconfig.compilerOptions.paths - support project references defined
tsconfig.references - support template variable ${configDir} for substitution of config files directory path
- support
compilerOptions.customConditionsandcompilerOptions.moduleSuffixes
- support extending tsconfig defined in
- Built-in tsconfig discovery (tsconfck) for
tsconfig.jsonandjsconfig.json, checked against TypeScript itself (see TypeScript Configuration) - Supports in-memory file system via the
FileSystemtrait. - Contains
tracinginstrumentation.
See index.d.ts for resolveSync and ResolverFactory API.
Quick example:
import assert from "assert";
import path from "path";
import resolve, { ResolverFactory } from "./index.js";
// `resolve`
assert(resolve.sync(process.cwd(), "./index.js").path, path.join(cwd, "index.js"));
// `ResolverFactory`
const resolver = new ResolverFactory();
assert(resolver.sync(process.cwd(), "./index.js").path, path.join(cwd, "index.js"));For file-based resolution with automatic tsconfig discovery, use resolveFileSync or resolveFileAsync:
const resolver = new ResolverFactory({ tsconfig: "auto" });
// Resolves from a file path (not directory)
const result = resolver.resolveFileSync("/path/to/file.ts", "./module");
// Async version
const result = await resolver.resolveFileAsync("/path/to/file.ts", "./module");Key Differences:
sync(directory, specifier)- Takes a directory path, uses manually configured tsconfig if providedresolveFileSync(file, specifier)- Takes a file path, withtsconfig: "auto"discovers the tsconfig of that file
Why use resolveFileSync?
When resolving from a specific file (e.g., in bundlers, linters, or language servers), resolveFileSync with tsconfig: "auto" finds the tsconfig of that file the way TypeScript finds the project of a file that is open in an editor:
- It starts at the nearest
tsconfig.jsonorjsconfig.jsonabove the file, and goes further up when that one does not have the file. - It follows project
references, also the ones of a referenced project. - The tsconfig that lists the file through
files,includeandexcludeis the one that applies. - A file that no tsconfig lists gets the nearest tsconfig. With
tsconfig: "auto-strict"it gets none. paths,baseUrl,rootDirs,customConditionsandmoduleSuffixesof that tsconfig then apply to the resolution.
Use findTsconfigSync or findTsconfigAsync to load the tsconfig associated with a source
file. The resolver reuses its internal cache across lookups:
import { ResolverFactory } from "oxc-resolver";
const resolver = new ResolverFactory({ tsconfig: "auto" });
const result = resolver.findTsconfigSync("/path/to/file.ts");
const asyncResult = await resolver.findTsconfigAsync("/path/to/file.ts");
if (result) console.log(result.tsconfigFilePaths, result.tsconfig);
// In watch mode, after a tsconfig file changes:
resolver.clearCache();Pass tsconfig: { configFile: path } to use a specific configuration instead of automatic
discovery. Files inside node_modules are not associated with a tsconfig.
See https://stackblitz.com/edit/oxc-resolver for usage example.
See docs.rs/oxc_resolver.
- For node.js, yarn pnp should work without any configuration, given the following conditions:
- the program is called with the
yarncommand, where the valueprocess.versions.pnpis set. .pnp.cjsmanifest file exists in the closest directory, searched from the current working directory,- no multi-project setup, per second bullet point in FIND_PNP_MANIFEST
- the program is called with the
Package-map resolution is enabled automatically when Node's --experimental-package-map option is
passed on the command line or through NODE_OPTIONS. Command-line options take precedence.
Rust callers can supply the map through ResolveOptions::package_map. Package managers can generate
the map and inject the option by enabling
nodeExperimentalPackageMap in pnpm or
nodeExperimentalPackageMap in Yarn.
An absolute path to a directory where the specifier is resolved against.
For CommonJS modules, it is the __dirname variable that contains the absolute path to the folder containing current module.
For ECMAScript modules, it is the value of import.meta.url.
Behavior is undefined when given a path to a file.
The string passed to require or import, i.e. require("specifier") or import "specifier"
Error: Package subpath '.' is not defined by "exports" in- occurs when resolving withoutconditionNames.
The following usages apply to both Rust and Node.js; the code snippets are written in JavaScript.
To handle the exports field in package.json, ESM and CJS need to be differentiated.
defaultConditions is the conditional environment name array, ["node", "import"].
This means when the caller is an ESM import (import "module"), resolve options should be
{
"conditionNames": ["node", "import"]
}LOAD_PACKAGE_EXPORTS(X, DIR)
- let MATCH = PACKAGE_EXPORTS_RESOLVE(pathToFileURL(DIR/NAME), "." + SUBPATH,
package.json"exports", ["node", "require"]) defined in the ESM resolver.
This means when the caller is a CJS require (require("module")), resolve options should be
{
"conditionNames": ["node", "require"]
}To support both CJS and ESM with the same cache:
const esmResolver = new ResolverFactory({
conditionNames: ["node", "import"],
});
const cjsResolver = esmResolver.cloneWithOptions({
conditionNames: ["node", "require"],
});From this non-standard spec:
The
browserfield is provided to JavaScript bundlers or component tools when packaging modules for client side use.
The option is
{
"aliasFields": ["browser"]
}{
"mainFields": ["module", "main"]
}Quoting esbuild's documentation:
main- This is the standard field for all packages that are meant to be used with node. The name main is hard-coded in to node's module resolution logic itself. Because it's intended for use with node, it's reasonable to expect that the file path in this field is a CommonJS-style module.module- This field came from a proposal for how to integrate ECMAScript modules into node. Because of this, it's reasonable to expect that the file path in this field is an ECMAScript-style module. This proposal wasn't adopted by node (node uses "type": "module" instead) but it was adopted by major bundlers because ECMAScript-style modules lead to better tree shaking, or dead code removal.browser- This field came from a proposal that allows bundlers to replace node-specific files or modules with their browser-friendly versions. It lets you specify an alternate browser-specific entry point. Note that it is possible for a package to use both the browser and module field together (see the note below).
The following options are aligned with enhanced-resolve, and is implemented for Rust crate usage.
See index.d.ts for Node.js usage.
| Field | Default | Description |
|---|---|---|
| alias | {} | A hash map of module alias configurations |
| aliasFields | [] | A list of alias fields in description files |
| extensionAlias | {} | An object which maps extension to extension aliases |
| conditionNames | [] | A list of exports field condition names |
| enforceExtension | false | Enforce that an extension from extensions must be used |
| exportsFields | ["exports"] | A list of exports fields in description files |
| extensions | [".js", ".json", ".node"] | A list of extensions which should be tried for files |
| fallback | {} | Same as alias, but only used if default resolving fails |
| fileSystem | The file system which should be used | |
| fullySpecified | false | Request passed to resolve is already fully specified and extensions or main files are not resolved for it (they are still resolved for internal requests) |
| mainFields | ["main"] | A list of main fields in description files |
| mainFiles | ["index"] | A list of main files in directories |
| modules | ["node_modules"] | A list of directories to resolve modules from, can be absolute path or folder name. Absolute NODE_PATH entries are appended automatically when set. |
| resolveToContext | false | Resolve to a context instead of a file |
| preferRelative | false | Prefer to resolve module requests as relative request and fallback to resolving as module |
| preferAbsolute | false | Prefer to resolve server-relative urls as absolute paths before falling back to resolve in roots |
| restrictions | [] | A list of resolve restrictions |
| roots | [] | A list of root paths |
| symlinks | true | Whether to resolve symlinks to their symlinked location |
| allowPackageExportsInDirectoryResolve | false | Allow exports field in require('../directory'). Not part of enhanced-resolve. |
| typesVersions | 'latest' | Match typesVersions and types@<range> conditions in resolveDts*: 'latest', a TypeScript version like '6.0.3', or false to ignore. |
| Field | Default | Description |
|---|---|---|
| tsconfig | None | Which tsconfig applies: 'auto', 'auto-strict', or an object that names one. Without it no tsconfig is read. |
| tsconfig: 'auto' | Discover the tsconfig of the importing file (resolveFile*, resolveDts*, findTsconfig*). A file that no tsconfig lists gets the nearest tsconfig.json or jsconfig.json. |
|
| tsconfig: 'auto-strict' | Like 'auto', but a file that no tsconfig lists gets no tsconfig, which is what TypeScript does for a file nothing imports. |
|
| tsconfig.configFile | Use this tsconfig for every file. A relative path to the tsconfig file based on cwd, or an absolute path to the tsconfig file. |
|
| tsconfig.references | None | 'auto': follow the references of the tsconfig, so that a file gets the referenced project that lists it. Left out: references are not followed. |
In Rust these are TsconfigDiscovery::Auto, TsconfigDiscovery::AutoStrict and TsconfigDiscovery::Manual(TsconfigOptions).
What is read from a tsconfig:
| Field | Use |
|---|---|
extends |
A path, a package or an array of them. A target that is missing or circular is skipped and reported in TsConfig::diagnostics(); the rest applies. |
files, include, exclude |
Decide which tsconfig a file belongs to, with TypeScript's matching rules. Without exclude, outDir and declarationDir are excluded. |
references |
Followed as a graph, nested references and cycles included. |
compilerOptions.paths, baseUrl, rootDirs |
Map a specifier before it is resolved. ${configDir} is substituted. |
compilerOptions.customConditions |
Conditions that match in the exports and imports of a package.json, on top of conditionNames. |
compilerOptions.moduleSuffixes |
Suffixes to look for before the extension of a file: with [".ios", ""], ./util is util.ios.ts when that exists and util.ts otherwise. |
compilerOptions.allowJs |
Whether the tsconfig lists JavaScript files. On by default in a jsconfig.json. |
The other compilerOptions of findTsconfig* |
Not used for resolution. They are inherited through extends and returned for tools that transform code. |
A key set to null is not inherited through extends, as in TypeScript.
just conformance runs TypeScript and oxc-resolver over the projects in fixtures/tsconfig-conformance and compares, for each import, the tsconfig the importing file belongs to and what the specifier resolves to. The differences below are kept on purpose. A scenario that runs into one marks it as a deviation, with the reason.
- A file that no tsconfig lists gets the nearest tsconfig (
'auto'). TypeScript has such a file in the project of the file that imports it, and a resolver does not know who imports a file.'auto-strict'gives it no tsconfig instead. - A file TypeScript does not compile (
.vue,.svelte, a.jsfile withoutallowJs) gets the project around it ('auto'): the nearest tsconfig, or a tsconfig that one references when itsincludecovers the file. - An
includepattern that names an extension lists the files with that extension:src/**/*.vuelists.vuefiles. TypeScript only lists the extensions it compiles. baseUrlstill resolves. TypeScript 7 removed it.- A file inside
node_modulesgets no tsconfig, sopaths,customConditionsandmoduleSuffixesdo not apply to what a dependency imports. TypeScript applies the options of a project to every file of its program. extendsaccepts more: a directory that contains atsconfig.json, themainof apackage.json, and theimportcondition beforerequirewhen a package exports both.- A tsconfig that does not parse is not used. TypeScript uses what it can read of it. The nearest tsconfig of a file fails the resolution when it does not parse; one further up is skipped.
a.jsanda.d.tsstay in a project that also hasa.ts. TypeScript drops them, which takes a directory listing to know.includeandexcludematch case-insensitively on Windows and macOS, case-sensitively elsewhere. TypeScript asks the file system.moduleSuffixesapply to the files TypeScript resolves (.ts,.tsx,.d.ts,.js,.jsx,.json,.mts,.cts,.mjs,.cjs). Any other file is looked for by its own name, with or without""in the list. BothmoduleSuffixesandcustomConditionsapply whatevermoduleResolutionis.
| Field | Default | Description |
|---|---|---|
| descriptionFiles | ["package.json"] | A list of description files to read from |
| cachePredicate | function() { return true }; | A function which decides whether a request should be cached or not. An object is passed to the function with path and request properties. |
| cacheWithContext | true | If unsafe cache is enabled, includes request.context in the cache key |
| plugins | [] | A list of additional resolve plugins which should be applied |
| resolver | undefined | A prepared Resolver to which the plugins are attached |
| unsafeCache | false | Use this cache object to unsafely cache the successful requests |
The following environment variable emits tracing information for the oxc_resolver::resolve function.
e.g.
2024-06-11T07:12:20.003537Z DEBUG oxc_resolver: options: ResolveOptions { ... }, path: "...", specifier: "...", ret: "..."
at /path/to/oxc_resolver-1.8.1/src/lib.rs:212
in oxc_resolver::resolve with path: "...", specifier: "..."
The input values are options, path and specifier, the returned value is ret.
OXC_LOG=DEBUG your_program
RD_LOG='oxc_resolver' rolldown buildTests are ported from
- enhanced-resolve
- tsconfig-path and parcel-resolver for tsconfig-paths
Test cases are located in ./src/tests, fixtures are located in ./tests
- alias.test.js
- browserField.test.js
- dependencies.test.js
- exportsField.test.js
- extension-alias.test.js
- extensions.test.js
- fallback.test.js
- fullSpecified.test.js
- identifier.test.js (see unit test in
crates/oxc_resolver/src/request.rs) - importsField.test.js
- incorrect-description-file.test.js (need to add ctx.fileDependencies)
- missing.test.js
- path.test.js (see unit test in
crates/oxc_resolver/src/path.rs) - plugins.test.js
- pnp.test.js
- resolve.test.js
- restrictions.test.js (partially done, regex is not supported yet)
- roots.test.js
- scoped-packages.test.js
- simple.test.js
- symlink.test.js
Irrelevant tests
- CachedInputFileSystem.test.js
- SyncAsyncFileSystemDecorator.test.js
- forEachBail.test.js
- getPaths.test.js
- pr-53.test.js
- unsafe-cache.test.js
- yield.test.js
oxc_resolver is free and open-source software licensed under the MIT License.
Oxc partially copies code from the following projects.
| Project | License |
|---|---|
| webpack/enhanced-resolve | MIT |
| dividab/tsconfig-paths | MIT |
| parcel-bundler/parcel | MIT |
| tmccombs/json-comments-rs | Apache 2.0 |
| dominikg/tsconfck | MIT |