resolve-sync
v1.2.0
Published
Node module resolution that is flexible, synchronous and requires no builtin dependencies.
Maintainers
Readme
Installation
npm install resolve-syncUsage
import { resolveSync } from "resolve-sync";
const result = resolveSync(id, options);id: The module id or path to resolve (e.g."./file","some-pkg","#alias").options: An object controlling resolution (see below).
Features
This module is designed to optimize speed while resolving in the same way node and bundlers do.
It avoids using any node: built in modules to make using in any environment (including browsers) easy.
Supports
- main field (and other fields via
options.fields) - browser field
- custom extensions
- export conditions
- import conditions
Resolve Options
from: string (required)
The absolute path to the source file (not a directory) where the resolution is initiated. Determines the starting directory and influences relative resolution.
root?: string
An optional root boundary directory. Module resolution won't ascend beyond this directory when traversing parent paths. Defaults to / if unspecified.
external?: (id: string) => boolean
Optional function to mark module ids as external. When true is returned, that id is returned without resolution (useful for built-ins, peer dependencies, or virtual modules).
Defaults:
- In Node.js: uses
node:module'sisBuiltin(treats built-ins as external). - Elsewhere:
() => false(no externals).
const result = resolveSync("fs", {
from: "/project/src/index.js",
external: (id) => id === "fs", // treat 'fs' as external
});
// result === "fs"silent?: boolean
If silent is set to true, the resolver will suppress errors and return undefined when a module cannot be resolved, instead of throwing an exception. This is useful for optional dependencies or when you want to handle missing modules gracefully.
exts?: string[]
An optional array of file extensions to try when resolving files without explicit extensions. Defaults to:
[".js", ".json"];fields?: string[]
Specifies the priority order of package.json fields to look at when resolving package main entries. Defaults to:
["module", "main"]ifbrowserisfalseor unset.["browser", "module", "main"]ifbrowseristrue.
require?: boolean
When true, this flag enables require conditions in exports maps. Default is false.
browser?: boolean
Partially implements the package.json browser field specification.
- Prioritizes the
browserfield in package.json when selecting entry points. - Enables
browserremapping for internal paths (e.g.,browser: { "./main.js": "./shim.js" }).
Note: Remaps defined in the
browserfield are only applied when resolving the module as a dependency (e.g.,some-module/foo). They do not affect relative paths like./foothat are resolved from within the module itself. Module remaps in the browser field likewise are not supported.
conditions?: string[]
A list of custom export conditions to use during resolution of package exports and imports fields. These conditions are matched in order and function identically to how conditions are interpreted by the wonderful resolve.exports module.
fs?: { isFile(file: string): boolean; readPkg(file: string): unknown; realpath?(file: string): string; }
A partial filesystem interface used by the resolver. If running in node, and not provided, a default node:fs based implementation is used. Must implement:
isFile(file: string): boolean– checks if the file exists and is a file.readPkg(file: string): unknown– reads and parses a JSON file (e.g.,package.json).realpath?(file: string): string– optionally resolves symlinks or returns the canonical path.
preserveSymlinks?: boolean
For use with the --preserve-symlinks flag in Node.js, this option is false by default. If set to true, the resolver will return the symlinked path instead of resolving it to its real path.
Examples
Basic usage (in Node.js)
import { resolveSync } from "resolve-sync";
const result = resolveSync("./file", {
from: "/project/src/index.js",
});
console.log(result); // => "/project/src/file.js"Resolving with custom extensions
const result = resolveSync("./file", {
from: "/project/src/index.js",
exts: [".ts", ".js"],
});
// Tries ./file.ts, then ./file.jsResolving a package main entry
const result = resolveSync("some-pkg", {
from: "/project/src/index.js",
});
// Looks for /project/node_modules/some-pkg/package.json and resolves its main/module fieldResolving files for browser/client usage
const result = resolveSync("some-pkg", {
from: "/project/src/index.js",
browser: true,
});
// Adds the `browser` export condition.
// If no `exports` field is found will check the "browser" field in package.jsonResolving files for require/commonjs usage
const result = resolveSync("some-pkg", {
from: "/project/src/index.js",
require: true,
});
// Replaces the "node" export condition with "require".Resolving with custom fields
const result = resolveSync("some-pkg", {
from: "/project/src/index.js",
fields: ["module", "jsnext:main", "main"],
});
// Looks for "module", then "jsnext:main" and finally "main" in package.jsonResolving custom export/import conditions
const result = resolveSync("some-pkg", {
from: "/project/src/index.js",
conditions: ["worker"],
});
// Adds "worker" to conditions, in this case ["default", "worker", "import", "node"]
const importResult = resolveSync("#alias", {
from: "/project/src/index.js",
});
// Uses the "imports" field in the nearest package.json to find "#alias"Scope resolution under a root directory
const result = resolveSync("some-pkg", {
from: "/project/src/index.js",
root: "/project", // Do not search above /project
});
// Will not resolve modules outside of /projectUsage in other environments (e.g., browser, test, or virtual fs)
This module has no dependencies hard dependencies on node: apis and can easily be used
in browser environments (eg a repl). When doing so the fs option is required.
import { resolveSync } from "resolve-sync";
const files = {
"/project/src/file.js": "",
"/project/package.json": JSON.stringify({ main: "src/file.js" }),
};
const result = resolveSync("./file", {
from: "/project/src/index.js",
// Provide a minimal fs interface:
fs: {
isFile(file) {
return file in files;
},
readPkg(file) {
return JSON.parse(files[file]);
},
},
});
console.log(result); // => "/project/src/file.js"