These options change how modules are resolved. Webpack provides reasonable defaults, but it is possible to change the resolving in detail. Have a look atModule Resolution for more explanation of how the resolver works.
object
Configure how modules are resolved. For example, when callingimport 'lodash'
in ES2015, theresolve
options can change where webpack goes to look for'lodash'
(seemodules
).
webpack.config.js
module.exports={//... resolve:{// configuration options},};
object
Create aliases toimport
orrequire
certain modules more easily. For example, to alias a bunch of commonly usedsrc/
folders:
webpack.config.js
const path=require('path');module.exports={//... resolve:{ alias:{ Utilities: path.resolve(__dirname,'src/utilities/'), Templates: path.resolve(__dirname,'src/templates/'),},},};
Now, instead of using relative paths when importing like so:
import Utilityfrom'../../utilities/utility';
you can use the alias:
import Utilityfrom'Utilities/utility';
A trailing$
can also be added to the given object's keys to signify an exact match:
webpack.config.js
const path=require('path');module.exports={//... resolve:{ alias:{ xyz$: path.resolve(__dirname,'path/to/file.js'),},},};
which would yield these results:
import Test1from'xyz';// Exact match, so path/to/file.js is resolved and importedimport Test2from'xyz/file.js';// Not an exact match, normal resolution takes place
You can also use wildcards (*
) in your alias configuration to create more flexible mappings:
webpack.config.js
module.exports={//... resolve:{ alias:{'@*': path.resolve(__dirname,'src/*'),// maps @something to path/to/something},},};
This allows you to use imports like:
import Componentfrom'@components/Button';import utilsfrom'@utils/helpers';
The following table explains other cases:
alias: | import 'xyz' | import 'xyz/file.js' |
---|---|---|
{} | /abc/node_modules/xyz/index.js | /abc/node_modules/xyz/file.js |
{ xyz: '/abc/path/to/file.js' } | /abc/path/to/file.js | error |
{ xyz$: '/abc/path/to/file.js' } | /abc/path/to/file.js | /abc/node_modules/xyz/file.js |
{ xyz: './dir/file.js' } | /abc/dir/file.js | error |
{ xyz$: './dir/file.js' } | /abc/dir/file.js | /abc/node_modules/xyz/file.js |
{ xyz: '/some/dir' } | /some/dir/index.js | /some/dir/file.js |
{ xyz$: '/some/dir' } | /some/dir/index.js | /abc/node_modules/xyz/file.js |
{ xyz: './dir' } | /abc/dir/index.js | /abc/dir/file.js |
{ xyz: 'modu' } | /abc/node_modules/modu/index.js | /abc/node_modules/modu/file.js |
{ xyz$: 'modu' } | /abc/node_modules/modu/index.js | /abc/node_modules/xyz/file.js |
{ xyz: 'modu/some/file.js' } | /abc/node_modules/modu/some/file.js | error |
{ xyz: 'modu/dir' } | /abc/node_modules/modu/dir/index.js | /abc/node_modules/modu/dir/file.js |
{ xyz$: 'modu/dir' } | /abc/node_modules/modu/dir/index.js | /abc/node_modules/xyz/file.js |
index.js
may resolve to another file if defined in thepackage.json
.
/abc/node_modules
may resolve in/node_modules
too.
resolve.alias
takes precedence over other module resolutions.
null-loader
is deprecated in webpack 5. usealias: { xyz$: false }
or absolute pathalias: {[path.resolve(__dirname, './path/to/module')]: false }
[string]
values are supported since webpack 5.
module.exports={//... resolve:{ alias:{ _:[ path.resolve(__dirname,'src/utilities/'), path.resolve(__dirname,'src/templates/'),],},},};
Settingresolve.alias
tofalse
will tell webpack to ignore a module.
module.exports={//... resolve:{ alias:{'ignored-module':false,'./ignored-module':false,},},};
[string]: ['browser']
Specify a field, such asbrowser
, to be parsed according tothis specification.
webpack.config.js
module.exports={//... resolve:{ aliasFields:['browser'],},};
Configure resolve options by the type of module request.
Type:[type: string]: ResolveOptions
Example:
module.exports={// ... resolve:{ byDependency:{// ... esm:{ mainFields:['browser','module'],}, commonjs:{ aliasFields:['browser'],}, url:{ preferRelative:true,},},},};
boolean
Enables caching of successfully resolved requests, allowing cache entries to be revalidated.
webpack.config.js
module.exports={//... resolve:{ cache:true,},};
function(module) => boolean
A function which decides whether a request should be cached or not. An object is passed to the function withpath
andrequest
properties. It must return a boolean.
webpack.config.js
module.exports={//... resolve:{cachePredicate:(module)=>{// additional logicreturntrue;},},};
boolean
If unsafe cache is enabled, includesrequest.context
in the cache key. This option is taken into account by theenhanced-resolve
module.context
in resolve caching is ignored when resolve or resolveLoader plugins are provided. This addresses a performance regression.
string[]
Condition names forexports
field which defines entry points of a package.
webpack.config.js
module.exports={//... resolve:{ conditionNames:['require','node'],},};
Webpack will matchexport conditions that are listed within theresolve.conditionNames
array.
The key order in theexports
field is significant. During condition matching, earlier entries have higher priority and take precedence over later entries.
For example,
package.json
{"name":"foo","exports":{".":{"import":"./index-import.js","require":"./index-require.js","node":"./index-node.js"},"./bar":{"node":"./bar-node.js","require":"./bar-require.js"},"./baz":{"import":"./baz-import.js","node":"./baz-node.js"}}}
webpack.config.js
module.exports={//... resolve:{ conditionNames:['require','node'],},};
importing
'foo'
will resolve to'foo/index-require.js'
'foo/bar'
will resolve to'foo/bar-node.js'
as the"node"
key comes before"require"
key in the conditional exports object.'foo/baz'
will resolve to'foo/baz-node.js'
If you want to add your custom field names while still retaining the default Webpack values, you can use"..."
:
webpack.config.js
module.exports={//... resolve:{ conditionNames:['my-custom-condition','...'],},};
Alternatively, to prioritize the default conditions first, then add your custom conditions:
webpack.config.js
module.exports={//... resolve:{ conditionNames:['...','my-custom-condition'],},};
[string] = ['package.json']
The JSON files to use for descriptions.
webpack.config.js
module.exports={//... resolve:{ descriptionFiles:['package.json'],},};
boolean = false
Iftrue
, it will not allow extension-less files. So by defaultrequire('./foo')
works if./foo
has a.js
extension, but with this enabled onlyrequire('./foo.js')
will work.
webpack.config.js
module.exports={//... resolve:{ enforceExtension:false,},};
[string] = ['exports']
Fields in package.json that are used for resolving module requests. Seepackage-exports guideline for more information.
webpack.config.js
module.exports={//... resolve:{ exportsFields:['exports','myCompanyExports'],},};
object
An object which maps extension to extension aliases.
webpack.config.js
module.exports={//... resolve:{ extensionAlias:{'.js':['.ts','.js'],'.mjs':['.mts','.mjs'],},},};
[string] = ['.js', '.json', '.wasm']
Attempt to resolve these extensions in order. If multiple files share the same name but have different extensions, webpack will resolve the one with the extension listed first in the array and skip the rest.
webpack.config.js
module.exports={//... resolve:{ extensions:['.js','.json','.wasm'],},};
which is what enables users to leave off the extension when importing:
import Filefrom'../path/to/file';
Note that usingresolve.extensions
like above willoverride the default array, meaning that webpack will no longer try to resolve modules using the default extensions. However you can use'...'
to access the default extensions:
module.exports={//... resolve:{ extensions:['.ts','...'],},};
object
Redirect module requests when normal resolving fails.
webpack.config.js
module.exports={//... resolve:{ fallback:{ abc:false,// do not include a polyfill for abc xyz: path.resolve(__dirname,'path/to/file.js'),// include a polyfill for xyz},},};
Webpack 5 no longer polyfills Node.js core modules automatically which means if you use them in your code running in browsers or alike, you will have to install compatible modules from npm and include them yourself. Here is a list of polyfills webpack has used before webpack 5:
module.exports={//... resolve:{ fallback:{ assert: require.resolve('assert'), buffer: require.resolve('buffer'), console: require.resolve('console-browserify'), constants: require.resolve('constants-browserify'), crypto: require.resolve('crypto-browserify'), domain: require.resolve('domain-browser'), events: require.resolve('events'), http: require.resolve('stream-http'), https: require.resolve('https-browserify'), os: require.resolve('os-browserify/browser'), path: require.resolve('path-browserify'), punycode: require.resolve('punycode'), process: require.resolve('process/browser'), querystring: require.resolve('querystring-es3'), stream: require.resolve('stream-browserify'), string_decoder: require.resolve('string_decoder'), sys: require.resolve('util'), timers: require.resolve('timers-browserify'), tty: require.resolve('tty-browserify'), url: require.resolve('url'), util: require.resolve('util'), vm: require.resolve('vm-browserify'), zlib: require.resolve('browserify-zlib'),},},};
boolean
When set to true, this option treats user-specified requests as fully specified. This means that no extensions are automatically added, and the mainFiles within directories are not resolved. It's important to note that this behavior does not affect requests made throughmainFields
,aliasFields
, oraliases
.
webpack.config.js
module.exports={//... resolve:{ fullySpecified:true,},};
[string]
Fields frompackage.json
which are used to provide the internal requests of a package (requests starting with#
are considered internal).
webpack.config.js
module.exports={//... resolve:{ importsFields:['browser','module','main'],},};
[string]
When importing from an npm package, e.g.import * as D3 from 'd3'
, this option will determine which fields in itspackage.json
are checked. The default values will vary based upon thetarget
specified in your webpack configuration.
When thetarget
property is set towebworker
,web
, or left unspecified:
webpack.config.js
module.exports={//... resolve:{ mainFields:['browser','module','main'],},};
For any other target (includingnode
):
webpack.config.js
module.exports={//... resolve:{ mainFields:['module','main'],},};
For example, consider an arbitrary library calledupstream
with apackage.json
that contains the following fields:
{"browser":"build/upstream.js","module":"index"}
When weimport * as Upstream from 'upstream'
this will actually resolve to the file in thebrowser
property. Thebrowser
property takes precedence because it's the first item inmainFields
. Meanwhile, a Node.js application bundled by webpack will first try to resolve using the file in themodule
field.
[string] = ['index']
The filename to be used while resolving directories.
webpack.config.js
module.exports={//... resolve:{ mainFiles:['index'],},};
[string] = ['node_modules']
Tell webpack what directories should be searched when resolving modules.
Absolute and relative paths can both be used, but be aware that they will behave a bit differently.
A relative path will be scanned similarly to how Node scans fornode_modules
, by looking through the current directory as well as its ancestors (i.e../node_modules
,../node_modules
, and on).
With an absolute path, it will only search in the given directory.
webpack.config.js
module.exports={//... resolve:{ modules:['node_modules'],},};
If you want to add a directory to search in that takes precedence overnode_modules/
:
webpack.config.js
const path=require('path');module.exports={//... resolve:{ modules:[path.resolve(__dirname,'src'),'node_modules'],},};
A list of additional resolve plugins which should be applied. It allows plugins such asDirectoryNamedWebpackPlugin
.
webpack.config.js
module.exports={//... resolve:{ plugins:[newDirectoryNamedWebpackPlugin()],},};
boolean
Prefer absolute paths toresolve.roots
when resolving.
webpack.config.js
module.exports={//... resolve:{ preferAbsolute:true,},};
boolean
When enabled, webpack would prefer to resolve module requests as relative requests instead of using modules fromnode_modules
directories.
webpack.config.js
module.exports={//... resolve:{ preferRelative:true,},};
src/index.js
// let's say `src/logo.svg` existsimport logo1from'logo.svg';// this is viable when `preferRelative` enabledimport logo2from'./logo.svg';// otherwise you can only use relative path to resolve logo.svg// `preferRelative` is enabled by default for `new URL()` caseconst b=newURL('module/path',import.meta.url);const a=newURL('./module/path',import.meta.url);
[string, RegExp]
A list of resolve restrictions to restrict the paths that a request can be resolved on.
webpack.config.js
module.exports={//... resolve:{ restrictions:[/\.(sass|scss|css)$/],},};
[string]
A list of directories where requests of server-relative URLs (starting with '/') are resolved, defaults tocontext
configuration option. On non-Windows systems these requests are resolved as an absolute path first.
webpack.config.js
const fixtures= path.resolve(__dirname,'fixtures');module.exports={//... resolve:{ roots:[__dirname, fixtures],},};
boolean = true
Whether to resolve symlinks to their symlinked location.
When enabled, symlinked resources are resolved to theirreal path, not their symlinked location. Note that this may cause module resolution to fail when using tools that symlink packages (likenpm link
).
webpack.config.js
module.exports={//... resolve:{ symlinks:true,},};
object
boolean = true
Enable aggressive, butunsafe, caching of modules. Passingtrue
will cache everything.
webpack.config.js
module.exports={//... resolve:{ unsafeCache:true,},};
When an object is provided, webpack will use it as cache.
For example, you can supply aProxy object instead of a regular one:
webpack.config.js
// copied from discussion here https://github.com/webpack/webpack/discussions/18089const realUnsafeCache={};const unsafeCacheHandler={get(cache, key){const cachedValue= cache[key];// make sure the file exists on diskif(cachedValue&&!fs.existsSync(cachedValue.path)){// and if it doesn't, evict that cache entry.delete cache[key];returnundefined;}return cachedValue;},};const theProxiedCache=newProxy(realUnsafeCache, unsafeCacheHandler);module.exports={//... resolve:{ unsafeCache: theProxiedCache,},};
Changes to cached paths may cause failure in rare cases.
boolean
Use synchronous filesystem calls for the resolver.
webpack.config.js
module.exports={//... resolve:{ useSyncFileSystemCalls:true,},};
object { modules [string] = ['node_modules'], extensions [string] = ['.js', '.json'], mainFields [string] = ['loader', 'main']}
This set of options is identical to theresolve
property set above, but is used only to resolve webpack'sloader packages.
webpack.config.js
module.exports={//... resolveLoader:{ modules:['node_modules'], extensions:['.js','.json'], mainFields:['loader','main'],},};
Note that you can use alias here and other features familiar from resolve. For example{ txt: 'raw-loader' }
would shimtxt!templates/demo.txt
to useraw-loader
.