A resolver is a library which helps in locating a module by its absolute path. A module can be required as a dependency from another module as:
import foo from 'path/to/module';
// or
require('path/to/module');
The dependency module can be from the application code or a third-party library. The resolver helps
webpack find the module code that needs to be included in the bundle for every such require
/import
statement.
webpack uses enhanced-resolve to resolve file paths while bundling modules.
Using enhanced-resolve
, webpack can resolve three kinds of file paths:
import '/home/me/file';
import 'C:\\Users\\me\\file';
Since we already have the absolute path to the file, no further resolution is required.
import '../src/file1';
import './file2';
In this case, the directory of the resource file where the import
or require
occurs is taken to be the context directory. The relative path specified in the import/require
is joined to this context path to produce the absolute path to the module.
import 'module';
import 'module/lib/file';
Modules are searched for inside all directories specified in resolve.modules
.
You can replace the original module path by an alternate path by creating an alias for it using the resolve.alias
configuration option.
package.json
file, then fields specified in resolve.exportsFields
configuration options are looked up in order, and the first such field in package.json
determines the available exports from the package according to the package exports guideline.Once the path is resolved based on the above rule, the resolver checks to see if the path points to a file or a directory. If the path points to a file:
resolve.extensions
option, which tells the resolver which extensions are acceptable for resolution e.g. .js
, .jsx
.If the path points to a folder, then the following steps are taken to find the right file with the right extension:
package.json
file, then fields specified in resolve.mainFields
configuration option are looked up in order, and the first such field in package.json
determines the file path.package.json
or if the resolve.mainFields
do not return a valid path, file names specified in the resolve.mainFiles
configuration option are looked for in order, to see if a matching filename exists in the imported/required directory.resolve.extensions
option.webpack provides reasonable defaults for these options depending on your build target.
This follows the same rules as those specified for file resolution. But the resolveLoader
configuration option can be used to have separate resolution rules for loaders.
Every filesystem access is cached so that multiple parallel or serial requests to the same file occur faster. In watch mode, only modified files are evicted from the cache. If watch mode is off, then the cache gets purged before every compilation.
See Resolve API to learn more about the configuration options mentioned above.