{"name":"enhanced-resolve","version":"5.24.4","author":{"name":"Tobias Koppers @sokra"},"license":"MIT","_id":"enhanced-resolve@5.24.4","maintainers":[{"name":"15000621931","email":"784487301@qq.com"},{"name":"ev1stensberg","email":"evenstensberg@gmail.com"},{"name":"__hai","email":"haijie0619@gmail.com"},{"name":"sokra","email":"tobias.koppers@googlemail.com"},{"name":"avivkeller","email":"me@aviv.sh"},{"name":"evilebottnawi","email":"sheo13666q@gmail.com"},{"name":"jhnns","email":"mail@johannesewald.de"},{"name":"thelarkinn","email":"sean.larkin1@gmail.com"}],"homepage":"https://github.com/webpack/enhanced-resolve#readme","bugs":{"url":"https://github.com/webpack/enhanced-resolve/issues"},"dist":{"shasum":"ec1f25ece12a37cc299762b412fa6c5962d52227","tarball":"http://registry-npm.ywwl.com/enhanced-resolve/download/enhanced-resolve-5.24.4.tgz","fileCount":58,"integrity":"sha512-GVoi+ICHocoOIU7qVVM48wOJziRsqrsyqlI0Ce0LdowRn6v3bcH2zUa9kp85ncx0nwIb9/HOCOLS3fdThDG/XQ==","signatures":[{"sig":"MEUCIQC3BjCvg+XaF4D6mlwBTt15lHlJxUhzexUX5KIQ82eLrgIgSsHqFzKcHtWovb1a7OPeoAh+Ipi9vSo6rMPmIWYwU1s=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"},{"sig":"MEUCIQCiivWtKkfrdD+/5xCP11iNuF6JQlDmGLY9b9xMoVEwsQIgVWLp3ugbw0MqHcACyYVxLFKTQwaTeNyAAY41sZhGpfc=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"attestations":{"url":"https://registry.npmjs.org/-/npm/v1/attestations/enhanced-resolve@5.24.4","provenance":{"predicateType":"https://slsa.dev/provenance/v1"}},"unpackedSize":420139,"size":96777,"noattachment":false,"key":"/enhanced-resolve/-/enhanced-resolve-5.24.4.tgz"},"main":"lib/index.js","types":"types.d.ts","browser":{"url":"./lib/util/url-browser.js","path":"./lib/util/path-browser.js","module":"./lib/util/module-browser.js","process":"./lib/util/process-browser.js","graceful-fs":"./lib/util/graceful-fs-browser.js"},"engines":{"node":">=10.13.0"},"gitHead":"24c3521b2374ac34a1db3ca133f9d708e77bf185","scripts":{"fix":"npm run fix:code && npm run fix:special","fmt":"npm run fmt:base -- --log-level warn --write","lint":"npm run lint:code && npm run lint:types && npm run lint:types-test && npm run lint:special && npm run fmt:check && npm run lint:spellcheck","test":"npm run test:only","prepare":"husky","pretest":"npm run lint","release":"changeset publish","version":"changeset version","fix:code":"npm run lint:code -- --fix","fmt:base":"node_modules/prettier/bin/prettier.cjs --cache --ignore-unknown .","benchmark":"node --max-old-space-size=4096 --hash-seed=1 --random-seed=1 --no-opt --predictable --predictable-gc-schedule --interpreted-frames-native-stack --allow-natives-syntax --expose-gc --no-concurrent-sweeping ./benchmark/run.mjs","fmt:check":"npm run fmt:base -- --check","lint:code":"eslint --cache .","test:only":"node scripts/test.js","lint:types":"tsc","test:watch":"node scripts/test.js --watch","fix:special":"node node_modules/tooling/inherit-types --write && node node_modules/tooling/generate-types --write","type-report":"rimraf coverage && npm run cover:types && npm run cover:report && open-cli coverage/lcov-report/index.html","lint:special":"node node_modules/tooling/inherit-types && node node_modules/tooling/generate-types","test:browser":"node --experimental-vm-modules test/smoke/browser-run.cjs","test:coverage":"node scripts/test.js --experimental-test-coverage --test-coverage-include=\"lib/**\" --test-reporter=spec --test-reporter-destination=stdout --test-reporter=lcov --test-reporter-destination=coverage/lcov.info","lint:spellcheck":"cspell --cache --no-must-find-files --quiet \"**/*.*\"","lint:types-test":"tsc -p tsconfig.types.test.json"},"_npmUser":{"name":"GitHub Actions","email":"npm-oidc-no-reply@github.com","trustedPublisher":{"id":"github","oidcConfigId":"oidc:f9180a1e-4232-454c-9485-121d7a38b9b8"}},"repository":{"url":"git+https://github.com/webpack/enhanced-resolve.git","type":"git"},"_npmVersion":"11.16.0","description":"Offers a async require.resolve function. It's highly configurable.","directories":{},"lint-staged":{"*":["prettier --cache --write --ignore-unknown","cspell --cache --no-must-find-files"],"*.{js,cjs,mjs}":["eslint --cache --fix"]},"_nodeVersion":"24.18.0","dependencies":{"tapable":"^2.3.3","graceful-fs":"^4.2.4"},"_hasShrinkwrap":false,"devDependencies":{"husky":"^9.1.7","memfs":"^4.56.11","cspell":"^10.0.0","eslint":"^9.39.2","tooling":"github:webpack/tooling#v1.26.4","webpack":"^5.107.2","prettier":"^3.7.4","tinybench":"^6.0.0","typescript":"^6.0.2","@types/node":"^24.10.4","lint-staged":"^17.0.4","@codspeed/core":"^5.2.0","@changesets/cli":"^2.30.0","@types/graceful-fs":"^4.1.6","eslint-config-webpack":"^4.9.5","@changesets/get-github-info":"^0.8.0"},"_npmOperationalInternal":{"tmp":"tmp/enhanced-resolve_5.24.4_1785259372052_0.7875596796481417","host":"s3://npm-registry-packages-npm-production"},"readme":"# enhanced-resolve\n\n[![npm][npm]][npm-url]\n[![Build Status][build-status]][build-status-url]\n[![codecov][codecov-badge]][codecov-url]\n[![Install Size][size]][size-url]\n[![GitHub Discussions][discussion]][discussion-url]\n\nOffers an async require.resolve function. It's highly configurable.\n\n## Features\n\n- plugin system\n- provide a custom filesystem\n- sync and async node.js filesystems included\n\n## Getting Started\n\n### Install\n\n```sh\n# npm\nnpm install enhanced-resolve\n# or Yarn\nyarn add enhanced-resolve\n# or pnpm\npnpm add enhanced-resolve\n```\n\n### Resolve\n\nThere is a Node.js API which allows to resolve requests according to the Node.js resolving rules.\nSync, async (callback) and promise APIs are offered. A `create` method allows to create a custom resolve function.\n\n```js\nconst resolve = require(\"enhanced-resolve\");\n\nresolve(\"/some/path/to/folder\", \"module/dir\", (err, result) => {\n\tresult; // === \"/some/path/node_modules/module/dir/index.js\"\n});\n\nresolve.sync(\"/some/path/to/folder\", \"../../dir\");\n// === \"/some/path/dir/index.js\"\n\nconst result = await resolve.promise(\"/some/path/to/folder\", \"../../dir\");\n// === \"/some/path/dir/index.js\"\n\nconst myResolve = resolve.create({\n\t// or resolve.create.sync / resolve.create.promise\n\textensions: [\".ts\", \".js\"],\n\t// see more options below\n});\n\nmyResolve(\"/some/path/to/folder\", \"ts-module\", (err, result) => {\n\tresult; // === \"/some/node_modules/ts-module/index.ts\"\n});\n```\n\n### Public API\n\nAll of the following are exposed from `require(\"enhanced-resolve\")`.\n\n#### `resolve(context?, parent, specifier, resolveContext?, callback)`\n\nAsync Node-style resolver using the built-in defaults (`conditionNames: [\"node\"]`, `extensions: [\".js\", \".json\", \".node\"]`). Both `context` and `resolveContext` are optional, so the function accepts four shapes:\n\n```js\nresolve(context, parent, specifier, resolveContext, callback);\nresolve(context, parent, specifier, callback);\nresolve(parent, specifier, resolveContext, callback);\nresolve(parent, specifier, callback); // most common\n```\n\nThe `parent` / `specifier` naming mirrors the ECMAScript resolution terms (as in `import.meta.resolve(specifier, parent)`): `parent` is the location you resolve **from**, and `specifier` is the string being resolved.\n\n##### Arguments — what each one is and when to pass it\n\n| Argument         | Required | What it is                                                                                                                                                                                                                                           | When to pass it                                                                                                               |\n| ---------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |\n| `context`        | no       | Extra info about _who_ is requesting, e.g. `{ environments: [\"node+es3+es5+process+native\"] }`. Plugins can read arbitrary keys off it. When omitted, a built-in Node context is used.                                                               | Pass it only when a plugin you use reads from it. Most callers omit it.                                                       |\n| `parent`         | yes      | The absolute directory to resolve **from** — the location the `specifier` is relative to (the ECMAScript \"parent\", historically called the \"lookup start path\").                                                                                     | Always.                                                                                                                       |\n| `specifier`      | yes      | The string to resolve — a relative specifier (`./utils`), a bare module (`lodash/merge`), an alias, etc. (the ECMAScript \"specifier\", historically called the \"request\").                                                                            | Always.                                                                                                                       |\n| `resolveContext` | no       | A collector object the resolver writes into / reads from: `fileDependencies`, `contextDependencies`, `missingDependencies` (`Set`s it fills in), `log` (a function it calls for trace output).                                                       | Pass it when you need to know which files/dirs were touched (e.g. to set up a watcher) or want a log of the resolution steps. |\n| `callback`       | yes      | `(err, result, resolveRequest) => void`. `result` is the resolved absolute path (or `false` if the request resolves to an ignored module). `resolveRequest` is the full request object with `path`, `query`, `fragment`, `descriptionFilePath`, etc. | Always.                                                                                                                       |\n\n##### Minimal form — just `parent`, `specifier`, `callback`\n\n```js\nconst resolve = require(\"enhanced-resolve\");\n\nresolve(__dirname, \"./utils\", (err, result) => {\n\tif (err) throw err;\n\tresult; // === \"/abs/path/to/utils.js\"\n});\n```\n\n##### Inspecting the full result via the third callback argument\n\n```js\nresolve(__dirname, \"./utils?query#frag\", (err, result, resolveRequest) => {\n\tresult; // === \"/abs/path/to/utils.js?query#frag\" — path with query/fragment appended\n\tresolveRequest.path; // === \"/abs/path/to/utils.js\" (the bare path, no query/fragment)\n\tresolveRequest.query; // === \"?query\"  (empty string if the request has none)\n\tresolveRequest.fragment; // === \"#frag\"   (empty string if the request has none)\n\tresolveRequest.descriptionFilePath; // path to the nearest package.json, if any\n});\n```\n\n##### With `resolveContext` — collect dependencies and a log\n\nPass a `resolveContext` when you need the resolver to report back _what it looked at_. The `Set`s you provide are filled in during resolution, and `log` is called with each step:\n\n```js\nconst fileDependencies = new Set();\nconst missingDependencies = new Set();\nconst contextDependencies = new Set();\nconst logs = [];\n\nresolve(\n\t__dirname,\n\t\"./utils\",\n\t{\n\t\tfileDependencies, // files that were read/checked\n\t\tmissingDependencies, // paths that were probed but didn't exist\n\t\tcontextDependencies, // directories that were read\n\t\tlog: (msg) => logs.push(msg), // trace of each resolution step\n\t},\n\t(err, result) => {\n\t\tresult; // === \"/abs/path/to/utils.js\"\n\t\tfileDependencies; // Set { \".../utils.js\", \".../package.json\", ... }\n\t\tmissingDependencies; // Set { \".../utils\", \".../utils.json\", ... } (candidates tried)\n\t\t// `fileDependencies` / `missingDependencies` are exactly what you'd feed\n\t\t// a file watcher so a rebuild re-runs when any of them changes.\n\t},\n);\n```\n\n##### With a custom `context`\n\nPass a `context` when a plugin reads from it. The default resolver only uses `environments`, but custom plugins may key off anything you put here:\n\n```js\nresolve(\n\t{ environments: [\"node+es3+es5+process+native\"] }, // context\n\t__dirname,\n\t\"./utils\",\n\t(err, result) => {\n\t\tresult; // === \"/abs/path/to/utils.js\"\n\t},\n);\n```\n\n#### `resolve.sync(context?, parent, specifier, resolveContext?) => string | false`\n\nSynchronous variant. Throws on failure, returns `false` when the resolve yields no result.\n\n```js\nconst file = resolve.sync(__dirname, \"./utils\");\n```\n\n#### `resolve.promise(context?, parent, specifier, resolveContext?) => Promise<string | false>`\n\nPromise variant of `resolve`.\n\n```js\nconst file = await resolve.promise(__dirname, \"./utils\");\n```\n\n#### `resolve.create(options) => ResolveFunctionAsync`\n\nBuilds a customized async resolve function. Options are the same as for [`ResolverFactory.createResolver`](#resolver-options); `fileSystem` defaults to the built-in Node.js filesystem.\n\n```js\nconst resolveTs = resolve.create({ extensions: [\".ts\", \".tsx\", \".js\"] });\n\nresolveTs(__dirname, \"./component\", (err, result) => {\n\t// result === \"/abs/path/to/component.tsx\"\n});\n```\n\n#### `resolve.create.sync(options) => ResolveFunction`\n\nSync variant of `resolve.create`.\n\n```js\nconst resolveTsSync = resolve.create.sync({ extensions: [\".ts\", \".js\"] });\nconst file = resolveTsSync(__dirname, \"./component\");\n```\n\n#### `resolve.create.promise(options) => ResolveFunctionPromise`\n\nPromise variant of `resolve.create`.\n\n```js\nconst resolveTsPromise = resolve.create.promise({ extensions: [\".ts\", \".js\"] });\nconst file = await resolveTsPromise(__dirname, \"./component\");\n```\n\n#### `ResolverFactory.createResolver(options) => Resolver`\n\nLower-level factory. Returns a `Resolver` whose `resolve`, `resolveSync`, and `resolvePromise` methods accept `(context, parent, specifier, resolveContext, [callback])`. Use this when you need a reusable resolver instance or access to its `hooks` (see the [Plugins](#plugins) section). `fileSystem` is required here — the high-level `resolve.create` defaults it for you.\n\n```js\nconst fs = require(\"fs\");\nconst { CachedInputFileSystem, ResolverFactory } = require(\"enhanced-resolve\");\n\nconst resolver = ResolverFactory.createResolver({\n\tfileSystem: new CachedInputFileSystem(fs, 4000),\n\textensions: [\".js\", \".json\"],\n});\n\n// callback\nresolver.resolve({}, __dirname, \"./utils\", {}, (err, file) => {\n\t// ...\n});\n\n// sync (requires a sync fileSystem)\nconst fileSync = resolver.resolveSync({}, __dirname, \"./utils\");\n\n// promise\nconst filePromise = await resolver.resolvePromise({}, __dirname, \"./utils\", {});\n```\n\n#### `CachedInputFileSystem(fileSystem, duration)`\n\nWraps any Node-compatible `fs` to add an in-memory cache for `stat`, `readdir`, `readFile`, `readJson`, and `readlink`. `duration` is the cache TTL in milliseconds (typically `4000`). Call `.purge()` to invalidate, or `.purge(path)` / `.purge([path, ...])` to invalidate specific entries — do this whenever you know files changed (e.g. from a watcher).\n\n```js\nconst fs = require(\"fs\");\nconst { CachedInputFileSystem } = require(\"enhanced-resolve\");\n\nconst cachedFs = new CachedInputFileSystem(fs, 4000);\n// later, when files change:\ncachedFs.purge(\"/abs/path/to/changed-file.js\");\n```\n\n#### Exported plugins & helpers\n\nFor use with the `plugins` option or as standalone utilities:\n\n- `ResolverFactory` — see above.\n- `CachedInputFileSystem` — see above.\n- `CloneBasenamePlugin(source, target)` — joins the directory's basename onto the path. See [Built-in Plugins](#built-in-plugins).\n- `LogInfoPlugin(source)` — logs pipeline state at a hook; enable by passing a `log` function on the `resolveContext`.\n- `TsconfigPathsPlugin(options)` — applies `tsconfig.json` `paths` / `baseUrl` mappings; typically configured via the `tsconfig` resolver option instead.\n- `forEachBail(array, iterator, callback)` — bail-style async iterator used internally; useful when authoring plugins that try several candidates in order.\n\n```js\nconst { LogInfoPlugin } = require(\"enhanced-resolve\");\n\nconst resolver = ResolverFactory.createResolver({\n\tfileSystem: cachedFs,\n\textensions: [\".js\"],\n\tplugins: [new LogInfoPlugin(\"described-resolve\")],\n});\n\nresolver.resolve(\n\t{},\n\t__dirname,\n\t\"./utils\",\n\t{ log: (msg) => console.log(msg) },\n\t() => {},\n);\n```\n\n### Creating a Resolver\n\nThe easiest way to create a resolver is to use the `createResolver` function on `ResolveFactory`, along with one of the supplied File System implementations.\n\n```js\nconst fs = require(\"fs\");\nconst { CachedInputFileSystem, ResolverFactory } = require(\"enhanced-resolve\");\n\n// create a resolver\nconst myResolver = ResolverFactory.createResolver({\n\t// Typical usage will consume the `fs` + `CachedInputFileSystem`, which wraps Node.js `fs` to add caching.\n\tfileSystem: new CachedInputFileSystem(fs, 4000),\n\textensions: [\".js\", \".json\"],\n\t/* any other resolver options here. Options/defaults can be seen below */\n});\n\n// resolve a file with the new resolver\nconst context = {};\nconst parent = \"/Users/webpack/some/root/dir\"; // directory to resolve from\nconst specifier = \"./path/to-look-up.js\"; // string to resolve\nconst resolveContext = {};\n\n// callback\nmyResolver.resolve(\n\tcontext,\n\tparent,\n\tspecifier,\n\tresolveContext,\n\t(err /* Error */, filepath /* string */) => {\n\t\t// Do something with the path\n\t},\n);\n\n// promise\ntry {\n\tconst filepath = await myResolver.resolvePromise(\n\t\tcontext,\n\t\tparent,\n\t\tspecifier,\n\t\tresolveContext,\n\t);\n\t// Do something with the path\n} catch (err) {\n\t// handle resolve failure\n}\n\n// sync (requires a sync fileSystem, e.g. the default Node.js one)\nconst filepath = myResolver.resolveSync(context, parent, specifier);\n```\n\n#### Resolver Options\n\n| Field                    | Default                     | Description                                                                                                                                                                                                                                                                                 |\n| ------------------------ | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| alias                    | []                          | A list of module alias configurations or an object which maps key to value                                                                                                                                                                                                                  |\n| aliasFields              | []                          | A list of alias fields in description files                                                                                                                                                                                                                                                 |\n| extensionAlias           | {}                          | An object which maps extension to extension aliases                                                                                                                                                                                                                                         |\n| extensionAliasForExports | false                       | Also apply `extensionAlias` to paths resolved through the package.json `exports` field. Off by default (Node.js-aligned)                                                                                                                                                                    |\n| 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.                                                                                                                                               |\n| cacheWithContext         | true                        | If unsafe cache is enabled, includes `request.context` in the cache key                                                                                                                                                                                                                     |\n| conditionNames           | []                          | A list of exports field condition names                                                                                                                                                                                                                                                     |\n| descriptionFiles         | [\"package.json\"]            | A list of description files to read from                                                                                                                                                                                                                                                    |\n| enforceExtension         | false                       | Enforce that a extension from extensions must be used                                                                                                                                                                                                                                       |\n| exportsFields            | [\"exports\"]                 | A list of exports fields in description files                                                                                                                                                                                                                                               |\n| extensions               | [\".js\", \".json\", \".node\"]   | A list of extensions which should be tried for files                                                                                                                                                                                                                                        |\n| fallback                 | []                          | Same as `alias`, but only used if default resolving fails                                                                                                                                                                                                                                   |\n| fileSystem               |                             | The file system which should be used                                                                                                                                                                                                                                                        |\n| 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)                                                                                                                                   |\n| mainFields               | [\"main\"]                    | A list of main fields in description files                                                                                                                                                                                                                                                  |\n| mainFiles                | [\"index\"]                   | A list of main files in directories                                                                                                                                                                                                                                                         |\n| modules                  | [\"node_modules\"]            | A list of directories to resolve modules from, can be absolute path or folder name                                                                                                                                                                                                          |\n| plugins                  | []                          | A list of additional resolve plugins which should be applied                                                                                                                                                                                                                                |\n| resolver                 | undefined                   | A prepared Resolver to which the plugins are attached                                                                                                                                                                                                                                       |\n| resolveToContext         | false                       | Resolve to a context instead of a file                                                                                                                                                                                                                                                      |\n| preferRelative           | false                       | Prefer to resolve module requests as relative request and fallback to resolving as module                                                                                                                                                                                                   |\n| preferAbsolute           | false                       | Prefer to resolve server-relative urls as absolute paths before falling back to resolve in roots                                                                                                                                                                                            |\n| restrictions             | []                          | A list of resolve restrictions                                                                                                                                                                                                                                                              |\n| roots                    | []                          | A list of root paths                                                                                                                                                                                                                                                                        |\n| symlinks                 | true                        | Whether to resolve symlinks to their symlinked location                                                                                                                                                                                                                                     |\n| tsconfig                 | false                       | TypeScript config for paths mapping. Can be `false` (disabled), `true` (use default `tsconfig.json`), a string path to `tsconfig.json`, or an object with `configFile`, `references`, and `baseUrl` options. Supports JSONC format (comments and trailing commas) like TypeScript compiler. |\n| tsconfig.configFile      | tsconfig.json               | Path to the tsconfig.json file                                                                                                                                                                                                                                                              |\n| tsconfig.references      | []                          | Project references. `'auto'` to load from tsconfig, or an array of paths to referenced projects                                                                                                                                                                                             |\n| tsconfig.baseUrl         | undefined                   | Override baseUrl from tsconfig.json. If provided, this value will be used instead of the baseUrl in the tsconfig file                                                                                                                                                                       |\n| unsafeCache              | false                       | Use this cache object to unsafely cache the successful requests                                                                                                                                                                                                                             |\n\n#### Option Examples\n\nSmall snippets for the non-obvious options. All options are passed to `resolve.create({ ... })` or `ResolverFactory.createResolver({ ... })`.\n\n**`alias`** — rewrite matching requests to a target path, module, or to `false` to ignore them. Accepts an object or an array of entries (array form lets you specify ordering / `onlyModule`).\n\n```js\nconst options = {\n\talias: {\n\t\t\"@\": path.resolve(__dirname, \"src\"), // @/utils → src/utils\n\t\tlodash$: \"lodash-es\", // exact \"lodash\", not \"lodash/foo\"\n\t\t\"ignored-module\": false, // short-circuit to an empty module\n\t},\n};\n```\n\n**`aliasFields`** — read alias maps from fields in `package.json`. The `browser` field is the common case:\n\n```js\nconst options = { aliasFields: [\"browser\"] };\n```\n\n**`extensionAlias`** — maps one request extension to a list of candidate extensions. Useful for TypeScript ESM where imports are written with `.js` but the source is `.ts`. Applies both to direct requests (e.g. `./foo.js`) and to paths produced by the package.json `imports` field (e.g. `#foo` → `./foo.js` → `./foo.ts`). By default it does **not** apply to paths produced by the `exports` field (to stay aligned with Node.js, which does not substitute extensions on package-exported paths) — see `extensionAliasForExports` below to opt in:\n\n```js\nconst options = {\n\textensionAlias: {\n\t\t\".js\": [\".ts\", \".js\"],\n\t\t\".mjs\": [\".mts\", \".mjs\"],\n\t},\n};\n```\n\n**`extensionAliasForExports`** — when `true`, also apply `extensionAlias` to paths resolved through the package.json `exports` field. Off by default to match Node.js. Turn it on if you want full alignment with TypeScript's resolver for packages that ship `.ts` sources alongside the compiled `.js` files they list in `exports` (e.g. monorepo source packages, or the `eslint-import-resolver-typescript` use case):\n\n```js\nconst options = {\n\textensionAlias: { \".js\": [\".ts\", \".js\"] },\n\textensionAliasForExports: true,\n};\n```\n\n**`conditionNames` + `exportsFields`** — pick which conditions to match in the `exports` field of `package.json`:\n\n```js\nconst options = {\n\tconditionNames: [\"import\", \"node\", \"default\"],\n\texportsFields: [\"exports\"],\n};\n```\n\n**`extensions`** — extensions to try for extensionless requests, in order:\n\n```js\nconst options = { extensions: [\".ts\", \".tsx\", \".js\", \".json\"] };\n```\n\n**`fallback`** — same shape as `alias`, but only consulted when the primary resolve fails. Handy for polyfills:\n\n```js\nconst options = {\n\tfallback: {\n\t\tcrypto: require.resolve(\"crypto-browserify\"),\n\t\tstream: false,\n\t},\n};\n```\n\n**`modules`** — where to look for bare-module requests. Entries can be folder names (searched hierarchically up the tree) or absolute paths (searched directly):\n\n```js\nconst options = { modules: [path.resolve(__dirname, \"src\"), \"node_modules\"] };\n```\n\n**`mainFields` / `mainFiles`** — fields in `package.json` to try for a package entry point, and filenames to try inside a directory:\n\n```js\nconst options = {\n\tmainFields: [\"browser\", \"module\", \"main\"],\n\tmainFiles: [\"index\"],\n};\n```\n\n**`roots` + `preferAbsolute`** — resolve server-relative URLs (starting with `/`) against one or more root directories. With `preferAbsolute: true`, absolute-path resolution is tried before the roots are consulted.\n\n```js\nconst options = {\n\troots: [path.resolve(__dirname, \"public\")],\n\tpreferAbsolute: false,\n};\n```\n\n**`restrictions`** — reject results that don't satisfy at least one restriction. Accepts strings (path prefixes) or `RegExp`s:\n\n```js\nconst options = {\n\trestrictions: [path.resolve(__dirname, \"src\"), /\\.(js|ts)$/],\n};\n```\n\n**`tsconfig`** — apply TypeScript `paths` / `baseUrl` mappings. Either pass `true` to load `./tsconfig.json`, a path string, or a configuration object:\n\n```js\nconst options = {\n\ttsconfig: {\n\t\tconfigFile: path.resolve(__dirname, \"tsconfig.json\"),\n\t\treferences: \"auto\", // honor project references declared in tsconfig\n\t},\n};\n```\n\n**`symlinks`** — resolve to the real path by following symlinks. Set to `false` to keep the symlinked path (common for monorepo / pnpm layouts where you want module identity tied to the workspace location):\n\n```js\nconst options = { symlinks: false };\n```\n\n**`fullySpecified`** — require fully-specified requests (no extension inference, no `index` lookup) for non-internal requests. Matches Node.js ESM semantics:\n\n```js\nconst options = { fullySpecified: true };\n```\n\n**`unsafeCache`** — pass an object to use as an in-memory cache of successful resolves. Set to `true` to let the resolver allocate its own:\n\n```js\nconst options = {\n\tunsafeCache: {}, // or true\n\tcacheWithContext: false, // skip context in the cache key — faster, but only safe if context doesn't change the result\n};\n```\n\nTo observe whether a request was served from the cache, wrap the cache object in a `Proxy`. `UnsafeCachePlugin` reads entries with `cache[id]` (cache lookup) and writes them with `cache[id] = result` (cache store), so trapping `get` and `set` is enough to distinguish hits from misses:\n\n```js\nconst cache = {};\nconst observedCache = new Proxy(cache, {\n\tget(target, name, receiver) {\n\t\tconst hit = name in target;\n\t\tconsole.log(hit ? `[cache hit]  ${name}` : `[cache miss] ${name}`);\n\t\treturn Reflect.get(target, name, receiver);\n\t},\n\tset(target, name, value, receiver) {\n\t\tconsole.log(`[cache set]  ${name}`);\n\t\treturn Reflect.set(target, name, value, receiver);\n\t},\n});\n\nconst resolver = ResolverFactory.createResolver({\n\tfileSystem: new CachedInputFileSystem(fs, 4000),\n\textensions: [\".js\", \".json\"],\n\tunsafeCache: observedCache,\n});\n```\n\nThe `name` argument is the cache id — a `JSON.stringify`'d object containing `type`, `context`, `path`, `query`, `fragment`, and `request` — so you can parse it to report on specific resolves. Only successful resolves go through the cache; failures never touch it.\n\n**`fileSystem`** — any `fs`-compatible implementation. Usually `new CachedInputFileSystem(fs, 4000)`; can be a virtual filesystem (e.g. `memfs`) for testing:\n\n```js\nconst options = { fileSystem: new CachedInputFileSystem(require(\"fs\"), 4000) };\n```\n\n**`plugins`** — additional plugin instances appended to the pipeline. See [Plugins](#plugins):\n\n```js\nconst options = {\n\tplugins: [new TsconfigPathsPlugin({ configFile: \"./tsconfig.json\" })],\n};\n```\n\n## Plugins\n\nSimilar to `webpack`, the core of `enhanced-resolve` functionality is implemented as individual plugins that are executed using [`tapable`](https://github.com/webpack/tapable).\nThese plugins can extend the functionality of the library, adding other ways for files/contexts to be resolved.\n\nA plugin should be a `class` (or its ES5 equivalent) with an `apply` method. The `apply` method will receive a `resolver` instance, that can be used to hook in to the event system.\n\nPlugins are executed in a pipeline, and register which event they should be executed before/after. `source` is the name of the event that starts the pipeline, and `target` is what event this plugin should fire, which is what continues the execution of the pipeline. For a full view of how these plugin events form a chain, see `lib/ResolverFactory.js`, in the `//// pipeline ////` section.\n\n### Built-in Plugins\n\n`enhanced-resolve` ships with the following plugins. Most of them are wired up automatically by `ResolverFactory` based on the [resolver options](#resolver-options); the ones exported from the package entry (`TsconfigPathsPlugin`, `CloneBasenamePlugin`, `LogInfoPlugin`) are the ones you're most likely to use explicitly.\n\n| Plugin                                   | Purpose                                                                                                                              |\n| ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |\n| `AliasPlugin`                            | Replaces a matching request with one or more alternative targets. Powers the `alias` and `fallback` options.                         |\n| `AliasFieldPlugin`                       | Applies aliasing based on a field in the description file (e.g. the `browser` field). Powers `aliasFields`.                          |\n| `AppendPlugin`                           | Appends a string (typically an extension) to the current path. Used for `extensions`.                                                |\n| `CloneBasenamePlugin`                    | Joins the current directory basename onto the path (e.g. `/foo/bar` → `/foo/bar/bar`). Useful for directory-named main-file schemes. |\n| `ConditionalPlugin`                      | Forwards the request only when it matches a given partial request shape.                                                             |\n| `DescriptionFilePlugin`                  | Finds and loads the nearest description file (e.g. `package.json`) so other plugins can read its fields. Powers `descriptionFiles`.  |\n| `DirectoryExistsPlugin`                  | Only continues the pipeline if the current path is an existing directory.                                                            |\n| `ExportsFieldPlugin`                     | Resolves requests through the `exports` field of a package's description file. Powers `exportsFields` and `conditionNames`.          |\n| `ExtensionAliasPlugin`                   | Maps one extension to a list of alternative extensions (e.g. `.js` → `.ts`, `.js`). Powers `extensionAlias`.                         |\n| `FileExistsPlugin`                       | Only continues the pipeline if the current path is an existing file, and records the file as a dependency.                           |\n| `ImportsFieldPlugin`                     | Resolves `#name` requests through the `imports` field of the enclosing package.                                                      |\n| `JoinRequestPlugin`                      | Joins the current path with the current request into a new path.                                                                     |\n| `JoinRequestPartPlugin`                  | Splits a module request into module name + inner request, joining the inner request onto the path.                                   |\n| `LogInfoPlugin`                          | Emits verbose log output at a given pipeline step. Handy for debugging resolves via `resolveContext.log`.                            |\n| `MainFieldPlugin`                        | Uses a field in the description file (e.g. `main`) to point to the entry file of a package. Powers `mainFields`.                     |\n| `ModulesInHierarchicalDirectoriesPlugin` | Searches for a module by walking up parent directories (the standard `node_modules` lookup). Powers `modules`.                       |\n| `ModulesInRootPlugin`                    | Searches for a module in a single absolute directory. Powers absolute-path entries in `modules`.                                     |\n| `NextPlugin`                             | Forwards the request from one hook to another without modification — glue between pipeline steps.                                    |\n| `ParsePlugin`                            | Parses a raw request string into its components (path, query, fragment, module flag, etc.).                                          |\n| `PnpPlugin`                              | Resolves module requests through a Yarn PnP API when one is available.                                                               |\n| `RestrictionsPlugin`                     | Rejects results that don't match a list of path restrictions (strings or regular expressions). Powers `restrictions`.                |\n| `ResultPlugin`                           | Terminal plugin that fires the `result` hook — signals a successful resolve.                                                         |\n| `RootsPlugin`                            | Resolves server-relative URL requests (starting with `/`) against one or more root directories. Powers `roots`.                      |\n| `SelfReferencePlugin`                    | Resolves a package self-reference (e.g. `my-pkg/foo` from within `my-pkg`).                                                          |\n| `SymlinkPlugin`                          | Real paths the resolved file by following symlinks. Can be disabled via the `symlinks` option.                                       |\n| `TryNextPlugin`                          | Forwards the request to the next hook with a log message. Useful for trying alternative resolutions.                                 |\n| `TsconfigPathsPlugin`                    | Rewrites requests using the `paths` and `baseUrl` from a `tsconfig.json`. Powers the `tsconfig` option.                              |\n| `UnsafeCachePlugin`                      | Caches successful resolves in an in-memory map to speed up repeated requests. Powers `unsafeCache`.                                  |\n| `UseFilePlugin`                          | Joins a fixed filename onto the current path (e.g. `index`). Powers `mainFiles`.                                                     |\n\n#### Plugin wiring and goals\n\nOne-line goal and default wiring (`source → target`) for each plugin. `*` means the plugin is tapped on several hooks — the common ones are listed. Plugins without a fixed wiring are user-tapped.\n\n- **`AliasPlugin`** — Goal: redirect requests matching a configured key to an alternative target. `raw-resolve` → `internal-resolve` for `alias`; `file` → `internal-resolve` as a last-chance remap; `described-resolve` → `internal-resolve` for `fallback`.\n- **`AliasFieldPlugin`** — Goal: apply aliases declared in a description-file field like `browser`, so environment-specific substitutions happen without user config. `raw-resolve` / `file` → `internal-resolve`.\n- **`AppendPlugin`** — Goal: try appending a fixed string (usually an extension) to the current path. `raw-file` → `file`, one instance per entry in `extensions`.\n- **`CloneBasenamePlugin`** — Goal: join the directory's basename onto the path (e.g. `/foo/bar` → `/foo/bar/bar`) for directory-named-main layouts. User-wired via `plugins`.\n- **`ConditionalPlugin`** — Goal: gate a forward on a partial match of the request shape (e.g. `{ module: true }`), used to fan-out at branching hooks. Tapped on `after-normal-resolve`, `resolve-as-module`, `described-relative`, and `raw-file`.\n- **`DescriptionFilePlugin`** — Goal: locate and attach the nearest description file (usually `package.json`) so downstream plugins can read its fields. `parsed-resolve` → `described-resolve`, `relative` → `described-relative`, `undescribed-resolve-in-package` → `resolve-in-package`, `undescribed-existing-directory` → `existing-directory`, `undescribed-raw-file` → `raw-file`.\n- **`DirectoryExistsPlugin`** — Goal: only continue the pipeline if the current path exists as a directory. `resolve-as-module` → `undescribed-resolve-in-package`, `directory` → `undescribed-existing-directory`.\n- **`ExportsFieldPlugin`** — Goal: map a request through the `exports` field of a package's description file (with `conditionNames`). `resolve-in-package` → `relative`.\n- **`ExtensionAliasPlugin`** — Goal: rewrite a request's extension to a list of candidate extensions (e.g. `.js` → `.ts`, `.js`) for TypeScript ESM and similar. `raw-resolve` → `normal-resolve` for direct requests; also `imports-field-relative` → `relative` so extension substitution applies to `imports`-field targets.\n- **`FileExistsPlugin`** — Goal: confirm a candidate path exists as a file and record it as a file dependency. `final-file` → `existing-file`.\n- **`ImportsFieldPlugin`** — Goal: resolve `#name` requests through the `imports` field of the enclosing package. `internal` → `imports-field-relative` (relative target) or `imports-resolve` (bare target).\n- **`JoinRequestPlugin`** — Goal: join the current path with the current request into a single concrete path. `after-normal-resolve` → `relative` (three stage-offset copies for `preferRelative`, `preferAbsolute`, and default), `resolve-in-existing-directory` → `relative`.\n- **`JoinRequestPartPlugin`** — Goal: split a module request into module name + inner request, joining the inner part onto the path. `module` → `resolve-as-module`.\n- **`LogInfoPlugin`** — Goal: emit verbose log output at a chosen hook; enable by passing a `log` function on `resolveContext`. User-wired via `plugins`.\n- **`MainFieldPlugin`** — Goal: follow a description-file field (e.g. `main`, `module`, `browser`) to the entry file of a package. `existing-directory` → `resolve-in-existing-directory`, one instance per entry in `mainFields`.\n- **`ModulesInHierarchicalDirectoriesPlugin`** — Goal: search for a module by walking up parent directories (the standard `node_modules` lookup). `raw-module` → `module`; when PnP is enabled, `alternate-raw-module` → `module` too.\n- **`ModulesInRootPlugin`** — Goal: search for a module in a single absolute directory (powers absolute-path entries in `modules`). `raw-module` → `module`.\n- **`NextPlugin`** — Goal: glue — forward the current request unchanged from one hook to another. Used across the pipeline wherever two hooks should run sequentially.\n- **`ParsePlugin`** — Goal: split the raw request string into path / query / fragment / `module` / `directory` / `internal` flags. `resolve` → `parsed-resolve`; also wired on `internal-resolve` and `imports-resolve`.\n- **`PnpPlugin`** — Goal: resolve bare-module requests through Yarn's PnP API when available. `raw-module` → `undescribed-resolve-in-package` on hit, `alternate-raw-module` on miss.\n- **`RestrictionsPlugin`** — Goal: reject resolved paths that don't satisfy at least one string prefix or RegExp. Tapped on `resolved`.\n- **`ResultPlugin`** — Goal: terminal plugin — fires the `result` lifecycle hook and signals a successful resolve. Tapped on `resolved`.\n- **`RootsPlugin`** — Goal: resolve server-relative URL requests (starting with `/`) against one or more root directories. `after-normal-resolve` → `relative`.\n- **`SelfReferencePlugin`** — Goal: resolve a package self-reference (`my-pkg/foo` from inside `my-pkg`) via its own `exports`. `raw-module` → `resolve-as-module`.\n- **`SymlinkPlugin`** — Goal: real-path the resolved file by following symlinks; can be disabled via `symlinks: false`. `existing-file` → `existing-file` (runs via a stage offset on the same hook).\n- **`TryNextPlugin`** — Goal: forward the request to another hook with a log message, useful for trying an alternative candidate. `raw-file` → `file` (as the \"no extension\" attempt) and user-wired.\n- **`TsconfigPathsPlugin`** — Goal: rewrite requests using the `paths` and `baseUrl` from a `tsconfig.json` (including project references). Taps `described-resolve` internally and forwards to `internal-resolve`; exported for direct use as well.\n- **`UnsafeCachePlugin`** — Goal: cache successful resolves in an in-memory map for repeated requests. `described-resolve` → `raw-resolve` (only when `unsafeCache` is enabled).\n- **`UseFilePlugin`** — Goal: join a fixed filename (e.g. `index`) onto the current path to try as an entry file. `existing-directory` / `undescribed-existing-directory` → `undescribed-raw-file`, one instance per entry in `mainFiles`.\n\n### Hooks\n\nA resolver exposes two kinds of [`tapable`](https://github.com/webpack/tapable) hooks:\n\n- **Lifecycle hooks** on `resolver.hooks` — fired by the resolver itself around each `resolve` call. Use these to observe, not to transform the request.\n- **Pipeline hooks** — the named steps that plugins tap as `source` and forward to as `target`. Every pipeline hook is an `AsyncSeriesBailHook<[request, resolveContext], request | null>`: return `callback()` to pass on, `callback(err)` to fail, or `callback(null, request)` to short-circuit with a result. Obtain them with `resolver.ensureHook(name)` (creates if missing) or `resolver.getHook(name)` (throws if missing); names are kebab-case or camelCase and are interchangeable.\n\n#### Lifecycle hooks\n\n| Hook          | Type                  | Fires when                                                                                                                           |\n| ------------- | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |\n| `resolveStep` | `SyncHook`            | Every time the resolver hands a request to a pipeline hook. Arguments: `(hook, request)`. Ideal for tracing.                         |\n| `noResolve`   | `SyncHook`            | When a top-level `resolve()` call can't produce a result. Arguments: `(request, error)`.                                             |\n| `resolve`     | `AsyncSeriesBailHook` | Entry point of the pipeline (also listed below). Tap this to intercept requests before parsing.                                      |\n| `result`      | `AsyncSeriesHook`     | After a successful resolve, with the final request. Fired by `ResultPlugin`. Tap to observe/record results without short-circuiting. |\n\n#### Pipeline hooks\n\nListed roughly in the order the default pipeline visits them. Full wiring lives in `lib/ResolverFactory.js` under `//// pipeline ////`.\n\n| Hook                             | Role                                                                                                                                                                                      |\n| -------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `resolve`                        | Entry point. `ParsePlugin` parses the raw request (path, query, fragment, module flag) and forwards to `parsed-resolve`.                                                                  |\n| `internal-resolve`               | Re-entry point used by internal rewrites (e.g. after an `alias` fires). Same role as `resolve`, but `fullySpecified` is forced off.                                                       |\n| `imports-resolve`                | Re-entry point for the target of an `imports` field match; prevents recursive `#` resolution per the Node.js ESM spec.                                                                    |\n| `parsed-resolve`                 | Request has been parsed. `DescriptionFilePlugin` attaches the nearest `package.json`, then forwards to `described-resolve`.                                                               |\n| `described-resolve`              | Description file is attached. Where `unsafeCache`, `fallback`, and most user plugins (including `MyLibSrcPlugin` below) hook in.                                                          |\n| `raw-resolve`                    | After description. Where `alias`, `aliasFields`, `tsconfig` paths, and `extensionAlias` rewrites fire before default resolution.                                                          |\n| `normal-resolve`                 | Default resolution starts. Branches into `relative` (for `./`, `../`, absolute), `raw-module` (bare modules), or `internal` (`#imports`).                                                 |\n| `internal`                       | `#name` imports-field entry. `ImportsFieldPlugin` maps the specifier and forwards to `imports-field-relative` or `imports-resolve`.                                                       |\n| `imports-field-relative`         | Concrete path from an `imports`-field match, before the normal `relative` flow. `ExtensionAliasPlugin` taps here so `.js` → `.ts` also fires for `#name` targets. Forwards to `relative`. |\n| `raw-module`                     | Bare-module lookup. `SelfReferencePlugin`, `ModulesInHierarchicalDirectoriesPlugin`, `ModulesInRootPlugin`, and `PnpPlugin` all tap here.                                                 |\n| `alternate-raw-module`           | Fallback module lookup used by `PnpPlugin` when PnP can't resolve and `node_modules` should be tried.                                                                                     |\n| `module`                         | A candidate module directory was built. `JoinRequestPartPlugin` splits off the inner request and forwards to `resolve-as-module`.                                                         |\n| `resolve-as-module`              | Treat candidate as a package. `DirectoryExistsPlugin` gates on existence; short single-file modules may re-enter via `undescribed-raw-file`.                                              |\n| `undescribed-resolve-in-package` | Inside a located package directory, before its `package.json` has been read. Loads the description, forwards to `resolve-in-package`.                                                     |\n| `resolve-in-package`             | Inside a package with its description loaded. `ExportsFieldPlugin` matches `exports`, otherwise forwards to `resolve-in-existing-directory`.                                              |\n| `resolve-in-existing-directory`  | Package directory confirmed; join the remaining request onto it and continue at `relative`.                                                                                               |\n| `relative`                       | A concrete path on disk. `DescriptionFilePlugin` loads the nearest `package.json` and forwards to `described-relative`.                                                                   |\n| `described-relative`             | Branches to `raw-file` (treat as file) and `directory` (treat as directory). `resolveToContext` skips the file branch.                                                                    |\n| `directory`                      | Candidate directory. `DirectoryExistsPlugin` gates on existence and forwards to `undescribed-existing-directory`.                                                                         |\n| `undescribed-existing-directory` | Existing directory, before its `package.json` has been read. `UseFilePlugin` tries `mainFiles` via `undescribed-raw-file`.                                                                |\n| `existing-directory`             | Existing directory with description loaded. `MainFieldPlugin` tries `mainFields`; `UseFilePlugin` falls back to `mainFiles`.                                                              |\n| `undescribed-raw-file`           | Candidate file path, before description is read. Loads description, then forwards to `raw-file`.                                                                                          |\n| `raw-file`                       | Apply extension handling: `ConditionalPlugin` short-circuits when `fullySpecified`, `TryNextPlugin` + `AppendPlugin` try each extension.                                                  |\n| `file`                           | A specific file path. Last place `alias` and `aliasFields` can redirect; forwards to `final-file`.                                                                                        |\n| `final-file`                     | `FileExistsPlugin` checks the file is real and records it as a file dependency, then forwards to `existing-file`.                                                                         |\n| `existing-file`                  | Real file on disk. `SymlinkPlugin` real-paths symlinks (unless `symlinks: false`), then forwards to `resolved`.                                                                           |\n| `resolved`                       | Terminal hook. `RestrictionsPlugin` enforces `restrictions`; `ResultPlugin` fires the `result` lifecycle hook.                                                                            |\n\n#### `before-` and `after-` prefixes\n\n`ensureHook(\"before-foo\")` and `getHook(\"before-foo\")` return the `foo` hook with `stage: -10`; `after-foo` returns it with `stage: 10`. Use this to tap earlier or later than the default stage without creating a separate hook. You'll see `after-parsed-resolve`, `after-normal-resolve`, `after-relative`, and `after-undescribed-resolve-in-package` used this way inside `ResolverFactory`.\n\n#### Request flow by request type\n\nThe same 26 pipeline hooks serve every request, but different request shapes take different paths through them. Each `➝` below is one `doResolve` / `NextPlugin` / plugin forward; `resolveStep` fires on every arrow, so tapping it (see [Hook examples](#hook-examples)) prints these chains live.\n\nRelative path (`./utils` from `/src/index.js`) — the default \"resolve on disk\" path:\n\n```text\nresolve                                    (ParsePlugin)\n  ➝ parsed-resolve                         (DescriptionFilePlugin attaches nearest package.json)\n  ➝ described-resolve                      (NextPlugin; or UnsafeCachePlugin short-circuit)\n  ➝ raw-resolve                            (NextPlugin; alias/tsconfig would branch here)\n  ➝ normal-resolve                         (JoinRequestPlugin: path=/src/utils, request=\"\")\n  ➝ relative                               (DescriptionFilePlugin loads /src/package.json)\n  ➝ described-relative                     (branches to file and directory candidates)\n        ├─ ➝ raw-file                      (ConditionalPlugin / TryNextPlugin)\n        │     ➝ file                       (AppendPlugin tried each extension, e.g. .js)\n        │     ➝ final-file                 (FileExistsPlugin confirms the file)\n        │     ➝ existing-file              (SymlinkPlugin real-paths it)\n        │     ➝ resolved                   (RestrictionsPlugin → ResultPlugin)\n        └─ ➝ directory                     (DirectoryExistsPlugin; used when path is a dir)\n              ➝ undescribed-existing-directory\n              ➝ existing-directory         (MainFieldPlugin tries \"main\", UseFilePlugin tries \"index\")\n              ➝ undescribed-raw-file ➝ raw-file ➝ …\n```\n\nBare module (`lodash/merge`) — walks up `node_modules`, then treats the hit as a package:\n\n```text\nresolve ➝ parsed-resolve ➝ described-resolve ➝ raw-resolve ➝ normal-resolve\n  ➝ raw-module                             (ConditionalPlugin {module:true})\n  ➝ module                                 (ModulesInHierarchicalDirectoriesPlugin walks\n                                            /src/node_modules, /node_modules, …)\n  ➝ resolve-as-module                      (JoinRequestPartPlugin splits \"lodash\" / \"./merge\")\n  ➝ undescribed-resolve-in-package         (DirectoryExistsPlugin gates on lodash/ existing)\n  ➝ resolve-in-package                     (DescriptionFilePlugin loads lodash/package.json)\n        ├─ ➝ relative                      (ExportsFieldPlugin, if \"exports\" matches)\n        └─ ➝ resolve-in-existing-directory (otherwise; JoinRequestPlugin joins \"./merge\")\n              ➝ relative ➝ … (same tail as the relative flow above)\n```\n\nInternal import (`#util` from inside a package) — re-enters the pipeline after mapping:\n\n```text\nresolve ➝ parsed-resolve ➝ described-resolve ➝ raw-resolve ➝ normal-resolve\n  ➝ internal                               (ConditionalPlugin {internal:true})\n  ➝ imports-resolve                        (ImportsFieldPlugin mapped \"#util\" to a bare target)\n  ➝ parsed-resolve ➝ …                     (fresh pipeline run, internal:false so # isn't remapped)\n```\n\nWhen the `imports` field maps to a relative target, the branch instead goes:\n\n```text\n  ➝ internal\n  ➝ imports-field-relative                 (ImportsFieldPlugin mapped \"#util\" to \"./util.js\";\n                                            ExtensionAliasPlugin can swap .js → .ts here)\n  ➝ relative ➝ … (same tail as the relative flow above)\n```\n\nAlias hit (`@/button` with `alias: { \"@\": \"/src\" }`) — rewrites then restarts:\n\n```text\nresolve ➝ parsed-resolve ➝ described-resolve\n  ➝ raw-resolve\n  ➝ internal-resolve                       (AliasPlugin rewrote request → \"/src/button\")\n  ➝ parsed-resolve ➝ … (fullySpecified forced off; AliasPlugin won't re-fire for the rewritten form)\n```\n\n`exports`-field hit inside a package (`pkg/feature` matching `\"./feature\"` in `exports`):\n\n```text\n… ➝ raw-module ➝ module ➝ resolve-as-module ➝ undescribed-resolve-in-package\n  ➝ resolve-in-package\n  ➝ relative                               (ExportsFieldPlugin jumped to the exports target;\n                                            main-field / main-file logic is skipped)\n  ➝ described-relative ➝ raw-file ➝ file ➝ final-file ➝ existing-file ➝ resolved\n```\n\nFailure — every candidate opts out (`callback()`) and no handler ever short-circuits with a result. `noResolve` fires once, for the top-level request:\n\n```text\n… ➝ final-file\n       ✗ FileExistsPlugin: ENOENT  (opts out; no extension candidates left)\n  ⇠ bail hooks unwind, each tapped handler has already tried its alternatives\n  ⇒ top-level resolve() returns no result\n  ⇒ resolver.hooks.noResolve(request, error)    (ResultPlugin never fires)\n```\n\n#### Hook examples\n\nTrace every pipeline step and observe failures via the lifecycle hooks:\n\n```js\nresolver.hooks.resolveStep.tap(\"Trace\", (hook, request) => {\n\tconsole.log(`[step] ${hook.name}: ${request.request} @ ${request.path}`);\n});\nresolver.hooks.noResolve.tap(\"Trace\", (request, error) => {\n\tconsole.log(`[fail] ${request.request}: ${error.message}`);\n});\nresolver.hooks.result.tapAsync(\"Trace\", (request, _ctx, callback) => {\n\tconsole.log(`[done] ${request.path}`);\n\tcallback();\n});\n```\n\nShort-circuit at `file` to redirect any `.css` request to a stub without continuing the pipeline:\n\n```js\nclass StubCssPlugin {\n\tapply(resolver) {\n\t\tresolver\n\t\t\t.getHook(\"file\")\n\t\t\t.tapAsync(\"StubCssPlugin\", (request, _ctx, callback) => {\n\t\t\t\tif (!request.path || !request.path.endsWith(\".css\")) return callback();\n\t\t\t\tcallback(null, { ...request, path: require.resolve(\"./empty.css\") });\n\t\t\t});\n\t}\n}\n```\n\nForward to a different hook with `doResolve` to restart resolution with a rewritten request — see `MyLibSrcPlugin` in [Writing a Custom Plugin](#writing-a-custom-plugin) for the canonical pattern (`getHook(\"described-resolve\")` → `doResolve(ensureHook(\"resolve\"), …)`).\n\n### Writing a Custom Plugin\n\nThe example below adds a plugin that rewrites any request starting with `my-lib/` to `my-lib/src/`. It taps the `described-resolve` hook (after the description file has been located) and forwards the rewritten request to `resolve`, so the pipeline restarts with the new request.\n\n```js\nconst fs = require(\"fs\");\nconst { CachedInputFileSystem, ResolverFactory } = require(\"enhanced-resolve\");\n\nclass MyLibSrcPlugin {\n\tapply(resolver) {\n\t\tconst target = resolver.ensureHook(\"resolve\");\n\t\tresolver\n\t\t\t.getHook(\"described-resolve\")\n\t\t\t.tapAsync(\"MyLibSrcPlugin\", (request, resolveContext, callback) => {\n\t\t\t\tif (!request.request || !request.request.startsWith(\"my-lib/\")) {\n\t\t\t\t\treturn callback();\n\t\t\t\t}\n\t\t\t\tconst newRequest = {\n\t\t\t\t\t...request,\n\t\t\t\t\trequest: request.request.replace(/^my-lib\\//, \"my-lib/src/\"),\n\t\t\t\t};\n\t\t\t\tresolver.doResolve(\n\t\t\t\t\ttarget,\n\t\t\t\t\tnewRequest,\n\t\t\t\t\t\"rewrote my-lib → my-lib/src\",\n\t\t\t\t\tresolveContext,\n\t\t\t\t\tcallback,\n\t\t\t\t);\n\t\t\t});\n\t}\n}\n\nconst myResolver = ResolverFactory.createResolver({\n\tfileSystem: new CachedInputFileSystem(fs, 4000),\n\textensions: [\".js\", \".json\"],\n\tplugins: [new MyLibSrcPlugin()],\n});\n```\n\nTips for writing your own plugin:\n\n- Call `callback()` with no arguments to pass the request on to the next tapped handler at the same `source` hook. This is how you \"opt out\" when a request doesn't apply.\n- Call `resolver.doResolve(target, newRequest, message, resolveContext, callback)` to continue the pipeline at a different hook with a (possibly modified) request.\n- Return early with `callback(null, result)` to short-circuit with a specific result, or `callback(err)` to fail the resolve.\n- See [Hooks](#hooks) for the full list of pipeline hooks, their order, and the `before-` / `after-` stage modifiers. `lib/ResolverFactory.js` has the exact wiring under `//// pipeline ////`.\n\n## Escaping\n\nIt's allowed to escape `#` as `\\0#` to avoid parsing it as fragment.\n\nenhanced-resolve will try to resolve requests containing `#` as path and as fragment, so it will automatically figure out if `./some#thing` means `.../some.js#thing` or `.../some#thing.js`. When a `#` is resolved as path it will be escaped in the result. Here: `.../some\\0#thing.js`.\n\n## Tests\n\n```sh\nnpm run test\n```\n\n## Passing options from webpack\n\nIf you are using `webpack`, and you want to pass custom options to `enhanced-resolve`, the options are passed from the `resolve` key of your webpack configuration e.g.:\n\n```\nresolve: {\n  extensions: ['.js', '.jsx'],\n  modules: [path.resolve(__dirname, 'src'), 'node_modules'],\n  plugins: [new DirectoryNamedWebpackPlugin()]\n  ...\n},\n```\n\n## License\n\nCopyright (c) 2012-2019 JS Foundation and other contributors\n\nMIT (http://www.opensource.org/licenses/mit-license.php)\n\n[npm]: https://img.shields.io/npm/v/enhanced-resolve.svg\n[npm-url]: https://www.npmjs.com/package/enhanced-resolve\n[build-status]: https://github.com/webpack/enhanced-resolve/actions/workflows/test.yml/badge.svg\n[build-status-url]: https://github.com/webpack/enhanced-resolve/actions\n[codecov-badge]: https://codecov.io/gh/webpack/enhanced-resolve/branch/main/graph/badge.svg?token=6B6NxtsZc3\n[codecov-url]: https://codecov.io/gh/webpack/enhanced-resolve\n[size]: https://packagephobia.com/badge?p=enhanced-resolve\n[size-url]: https://packagephobia.com/result?p=enhanced-resolve\n[discussion]: https://img.shields.io/github/discussions/webpack/webpack\n[discussion-url]: https://github.com/webpack/webpack/discussions\n","publish_time":1785259372156,"_cnpm_publish_time":1785259372156,"dist-tags":{"beta":"5.0.0-beta.12","enhanced-resolve-4":"4.5.0","latest":"5.27.0"}}