You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

183 lines
11 KiB

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