UNPKG

11 kBMarkdownView Raw
1# enhanced-resolve
2
3[![npm][npm]][npm-url]
4[![Build Status][build-status]][build-status-url]
5[![codecov][codecov-badge]][codecov-url]
6[![Install Size][size]][size-url]
7[![GitHub Discussions][discussion]][discussion-url]
8
9Offers an async require.resolve function. It's highly configurable.
10
11## Features
12
13- plugin system
14- provide a custom filesystem
15- sync and async node.js filesystems included
16
17## Getting Started
18
19### Install
20
21```sh
22# npm
23npm install enhanced-resolve
24# or Yarn
25yarn add enhanced-resolve
26```
27
28### Resolve
29
30There is a Node.js API which allows to resolve requests according to the Node.js resolving rules.
31Sync and async APIs are offered. A `create` method allows to create a custom resolve function.
32
33```js
34const resolve = require("enhanced-resolve");
35
36resolve("/some/path/to/folder", "module/dir", (err, result) => {
37 result; // === "/some/path/node_modules/module/dir/index.js"
38});
39
40resolve.sync("/some/path/to/folder", "../../dir");
41// === "/some/path/dir/index.js"
42
43const myResolve = resolve.create({
44 // or resolve.create.sync
45 extensions: [".ts", ".js"]
46 // see more options below
47});
48
49myResolve("/some/path/to/folder", "ts-module", (err, result) => {
50 result; // === "/some/node_modules/ts-module/index.ts"
51});
52```
53
54### Creating a Resolver
55
56The easiest way to create a resolver is to use the `createResolver` function on `ResolveFactory`, along with one of the supplied File System implementations.
57
58```js
59const fs = require("fs");
60const { CachedInputFileSystem, ResolverFactory } = require("enhanced-resolve");
61
62// create a resolver
63const myResolver = ResolverFactory.createResolver({
64 // Typical usage will consume the `fs` + `CachedInputFileSystem`, which wraps Node.js `fs` to add caching.
65 fileSystem: new CachedInputFileSystem(fs, 4000),
66 extensions: [".js", ".json"]
67 /* any other resolver options here. Options/defaults can be seen below */
68});
69
70// resolve a file with the new resolver
71const context = {};
72const lookupStartPath = "/Users/webpack/some/root/dir";
73const request = "./path/to-look-up.js";
74const resolveContext = {};
75myResolver.resolve(context, lookupStartPath, request, resolveContext, (
76 err /*Error*/,
77 filepath /*string*/
78) => {
79 // Do something with the path
80});
81```
82
83#### Resolver Options
84
85| Field | Default | Description |
86|------------------|-----------------------------| --------------------------------------------------------------------------------------------------------------------------------------------------------- |
87| alias | [] | A list of module alias configurations or an object which maps key to value |
88| aliasFields | [] | A list of alias fields in description files |
89| extensionAlias | {} | An object which maps extension to extension aliases |
90| 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. |
91| cacheWithContext | true | If unsafe cache is enabled, includes `request.context` in the cache key |
92| conditionNames | [] | A list of exports field condition names |
93| descriptionFiles | ["package.json"] | A list of description files to read from |
94| enforceExtension | false | Enforce that a extension from extensions must be used |
95| exportsFields | ["exports"] | A list of exports fields in description files |
96| extensions | [".js", ".json", ".node"] | A list of extensions which should be tried for files |
97| fallback | [] | Same as `alias`, but only used if default resolving fails |
98| fileSystem | | The file system which should be used |
99| 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) |
100| mainFields | ["main"] | A list of main fields in description files |
101| mainFiles | ["index"] | A list of main files in directories |
102| modules | ["node_modules"] | A list of directories to resolve modules from, can be absolute path or folder name |
103| plugins | [] | A list of additional resolve plugins which should be applied |
104| resolver | undefined | A prepared Resolver to which the plugins are attached |
105| resolveToContext | false | Resolve to a context instead of a file |
106| preferRelative | false | Prefer to resolve module requests as relative request and fallback to resolving as module |
107| preferAbsolute | false | Prefer to resolve server-relative urls as absolute paths before falling back to resolve in roots |
108| restrictions | [] | A list of resolve restrictions |
109| roots | [] | A list of root paths |
110| symlinks | true | Whether to resolve symlinks to their symlinked location |
111| unsafeCache | false | Use this cache object to unsafely cache the successful requests |
112
113## Plugins
114
115Similar to `webpack`, the core of `enhanced-resolve` functionality is implemented as individual plugins that are executed using [`tapable`](https://github.com/webpack/tapable).
116These plugins can extend the functionality of the library, adding other ways for files/contexts to be resolved.
117
118A 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.
119
120### Plugin Boilerplate
121
122```js
123class MyResolverPlugin {
124 constructor(source, target) {
125 this.source = source;
126 this.target = target;
127 }
128
129 apply(resolver) {
130 const target = resolver.ensureHook(this.target);
131 resolver
132 .getHook(this.source)
133 .tapAsync("MyResolverPlugin", (request, resolveContext, callback) => {
134 // Any logic you need to create a new `request` can go here
135 resolver.doResolve(target, request, null, resolveContext, callback);
136 });
137 }
138}
139```
140
141Plugins are executed in a pipeline, and register which event they should be executed before/after. In the example above, `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 an example of how these different plugin events create a chain, see `lib/ResolverFactory.js`, in the `//// pipeline ////` section.
142
143## Escaping
144
145It's allowed to escape `#` as `\0#` to avoid parsing it as fragment.
146
147enhanced-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`.
148
149## Tests
150
151```javascript
152yarn test
153```
154
155## Passing options from webpack
156
157If 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.:
158
159```
160resolve: {
161 extensions: ['.js', '.jsx'],
162 modules: [path.resolve(__dirname, 'src'), 'node_modules'],
163 plugins: [new DirectoryNamedWebpackPlugin()]
164 ...
165},
166```
167
168## License
169
170Copyright (c) 2012-2019 JS Foundation and other contributors
171
172MIT (http://www.opensource.org/licenses/mit-license.php)
173
174[npm]: https://img.shields.io/npm/v/enhanced-resolve.svg
175[npm-url]: https://www.npmjs.com/package/enhanced-resolve
176[build-status]: https://github.com/webpack/enhanced-resolve/actions/workflows/test.yml/badge.svg?branch=master
177[build-status-url]: https://github.com/webpack/enhanced-resolve/actions
178[codecov-badge]: https://codecov.io/gh/webpack/enhanced-resolve/branch/main/graph/badge.svg?token=6B6NxtsZc3
179[codecov-url]: https://codecov.io/gh/webpack/enhanced-resolve
180[size]: https://packagephobia.com/badge?p=enhanced-resolve
181[size-url]: https://packagephobia.com/result?p=enhanced-resolve
182[discussion]: https://img.shields.io/github/discussions/webpack/webpack
183[discussion-url]: https://github.com/webpack/webpack/discussions