解析

这些选项更改了模块的解析方式。Webpack 提供了合理的默认值,但可以详细更改解析。请查看 模块解析 以了解解析器工作原理的更多说明。

resolve

object

配置模块的解析方式。例如,当在 ES2015 中调用 import 'lodash' 时,resolve 选项可以更改 webpack 查找 'lodash' 的位置(参见 modules)。

webpack.config.js

module.exports = {
  //...
  resolve: {
    // configuration options
  },
};

resolve.alias

object

创建别名以更轻松地 importrequire 特定模块。例如,为一组常用 src/ 文件夹创建别名

webpack.config.js

const path = require('path');

module.exports = {
  //...
  resolve: {
    alias: {
      Utilities: path.resolve(__dirname, 'src/utilities/'),
      Templates: path.resolve(__dirname, 'src/templates/'),
    },
  },
};

现在,不再使用相对路径进行导入,而是像这样

import Utility from '../../utilities/utility';

你可以使用别名

import Utility from 'Utilities/utility';

在给定对象的键后面添加一个 $ 符号可以表示精确匹配

webpack.config.js

const path = require('path');

module.exports = {
  //...
  resolve: {
    alias: {
      xyz$: path.resolve(__dirname, 'path/to/file.js'),
    },
  },
};

这将产生以下结果

import Test1 from 'xyz'; // Exact match, so path/to/file.js is resolved and imported
import Test2 from 'xyz/file.js'; // Not an exact match, normal resolution takes place

你也可以在别名配置中使用通配符(*)来创建更灵活的映射

webpack.config.js

module.exports = {
  //...
  resolve: {
    alias: {
      '@*': path.resolve(__dirname, 'src/*'), // maps @something to path/to/something
    },
  },
};

这允许你像这样使用导入

import Component from '@components/Button';
import utils from '@utils/helpers';

下表解释了其他情况

aliasimport '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.jserror
{ xyz$: '/abc/path/to/file.js' }/abc/path/to/file.js/abc/node_modules/xyz/file.js
{ xyz: './dir/file.js' }/abc/dir/file.jserror
{ 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.jserror
{ 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

如果 package.json 中有定义,index.js 可能会解析到另一个文件。

/abc/node_modules 也可能解析到 /node_modules

module.exports = {
  //...
  resolve: {
    alias: {
      _: [
        path.resolve(__dirname, 'src/utilities/'),
        path.resolve(__dirname, 'src/templates/'),
      ],
    },
  },
};

resolve.alias 设置为 false 将告诉 webpack 忽略一个模块。

module.exports = {
  //...
  resolve: {
    alias: {
      'ignored-module': false,
      './ignored-module': false,
    },
  },
};

resolve.aliasFields

[string]: ['browser']

指定一个字段,例如 browser,根据 此规范 进行解析。

webpack.config.js

module.exports = {
  //...
  resolve: {
    aliasFields: ['browser'],
  },
};

resolve.byDependency

根据模块请求的类型配置解析选项。

  • 类型:[type: string]: ResolveOptions

  • 示例

    module.exports = {
      // ...
      resolve: {
        byDependency: {
          // ...
          esm: {
            mainFields: ['browser', 'module'],
          },
          commonjs: {
            aliasFields: ['browser'],
          },
          url: {
            preferRelative: true,
          },
        },
      },
    };

resolve.cache

boolean

启用对成功解析请求的缓存,允许重新验证缓存条目。

webpack.config.js

module.exports = {
  //...
  resolve: {
    cache: true,
  },
};

resolve.cachePredicate

function(module) => boolean

一个函数,用于决定是否缓存请求。会将一个包含 pathrequest 属性的对象传递给该函数。它必须返回一个布尔值。

webpack.config.js

module.exports = {
  //...
  resolve: {
    cachePredicate: (module) => {
      // additional logic
      return true;
    },
  },
};

resolve.cacheWithContext

boolean

如果启用了不安全缓存,则将 request.context 包含在缓存键中。此选项由 enhanced-resolve 模块考虑。当提供了 resolve 或 resolveLoader 插件时,resolve 缓存中的 context 将被忽略。这解决了性能回退问题。

resolve.conditionNames

string[]

exports 字段的条件名称,它定义了包的入口点。

webpack.config.js

module.exports = {
  //...
  resolve: {
    conditionNames: ['require', 'node'],
  },
};

Webpack 将匹配 resolve.conditionNames 数组中列出的导出条件

exports 字段中的键顺序非常重要。在条件匹配期间,较早的条目具有更高的优先级并优先于较晚的条目。

例如,

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'],
  },
};

导入

  • 'foo' 将解析为 'foo/index-require.js'
  • 'foo/bar' 将解析为 'foo/bar-node.js',因为条件导出对象中 "node" 键在 "require" 键之前。
  • 'foo/baz' 将解析为 'foo/baz-node.js'

如果你想在保留默认 Webpack 值的同时添加自定义字段名,可以使用 "..."

webpack.config.js

module.exports = {
  //...
  resolve: {
    conditionNames: ['my-custom-condition', '...'],
  },
};

或者,优先使用默认条件,然后再添加自定义条件

webpack.config.js

module.exports = {
  //...
  resolve: {
    conditionNames: ['...', 'my-custom-condition'],
  },
};

resolve.descriptionFiles

[string] = ['package.json']

用于描述的 JSON 文件。

webpack.config.js

module.exports = {
  //...
  resolve: {
    descriptionFiles: ['package.json'],
  },
};

resolve.enforceExtension

boolean = false

如果设置为 true,将不允许没有扩展名的文件。因此,默认情况下,如果 ./foo.js 扩展名,require('./foo') 可以工作,但启用此选项后,只有 require('./foo.js') 才能工作。

webpack.config.js

module.exports = {
  //...
  resolve: {
    enforceExtension: false,
  },
};

resolve.exportsFields

[string] = ['exports']

package.json 中用于解析模块请求的字段。更多信息请参见 package-exports 指南

webpack.config.js

module.exports = {
  //...
  resolve: {
    exportsFields: ['exports', 'myCompanyExports'],
  },
};

resolve.extensionAlias

object

将扩展名映射到扩展别名的对象。

webpack.config.js

module.exports = {
  //...
  resolve: {
    extensionAlias: {
      '.js': ['.ts', '.js'],
      '.mjs': ['.mts', '.mjs'],
    },
  },
};

resolve.extensions

[string] = ['.js', '.json', '.wasm']

尝试按顺序解析这些扩展名。如果多个文件共享相同的名称但具有不同的扩展名,webpack 将解析数组中第一个列出的扩展名的文件,并跳过其余文件。

webpack.config.js

module.exports = {
  //...
  resolve: {
    extensions: ['.js', '.json', '.wasm'],
  },
};

这就是允许用户在导入时省略扩展名的原因

import File from '../path/to/file';

请注意,像上面这样使用 resolve.extensions 将会覆盖默认数组,这意味着 webpack 将不再尝试使用默认扩展名解析模块。但是你可以使用 '...' 来访问默认扩展名

module.exports = {
  //...
  resolve: {
    extensions: ['.ts', '...'],
  },
};

resolve.fallback

object

当正常解析失败时,重定向模块请求。

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 不再自动 polyfill Node.js 核心模块,这意味着如果你在浏览器或类似环境中运行的代码中使用它们,你将需要从 npm 安装兼容模块并自行包含它们。以下是 webpack 5 之前 webpack 使用的 polyfill 列表

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'),
    },
  },
};

resolve.fullySpecified

boolean

当设置为 true 时,此选项将用户指定的请求视为完全指定。这意味着不会自动添加扩展名,并且目录中的 mainFiles 不会被解析。需要注意的是,此行为不影响通过 mainFieldsaliasFieldsaliases 发出的请求。

webpack.config.js

module.exports = {
  //...
  resolve: {
    fullySpecified: true,
  },
};

resolve.importsFields

[string]

package.json 中用于提供包内部请求(以 # 开头的请求被视为内部请求)的字段。

webpack.config.js

module.exports = {
  //...
  resolve: {
    importsFields: ['browser', 'module', 'main'],
  },
};

resolve.mainFields

[string]

从 npm 包导入时,例如 import * as D3 from 'd3',此选项将决定检查其 package.json 中的哪些字段。默认值将根据 webpack 配置中指定的 target 而有所不同。

target 属性设置为 webworkerweb 或未指定时

webpack.config.js

module.exports = {
  //...
  resolve: {
    mainFields: ['browser', 'module', 'main'],
  },
};

对于任何其他目标(包括 node

webpack.config.js

module.exports = {
  //...
  resolve: {
    mainFields: ['module', 'main'],
  },
};

例如,考虑一个名为 upstream 的任意库,其 package.json 包含以下字段

{
  "browser": "build/upstream.js",
  "module": "index"
}

当我们 import * as Upstream from 'upstream' 时,它实际上将解析到 browser 属性中的文件。browser 属性优先,因为它在 mainFields 中是第一个条目。同时,由 webpack 打包的 Node.js 应用程序将首先尝试使用 module 字段中的文件进行解析。

resolve.mainFiles

[string] = ['index']

解析目录时使用的文件名。

webpack.config.js

module.exports = {
  //...
  resolve: {
    mainFiles: ['index'],
  },
};

resolve.modules

[string] = ['node_modules']

告诉 webpack 在解析模块时应该搜索哪些目录。

绝对路径和相对路径都可以使用,但请注意它们的行为会有所不同。

相对路径将以类似于 Node 扫描 node_modules 的方式进行扫描,通过查看当前目录及其父级目录(即 ./node_modules../node_modules 等)。

使用绝对路径时,它将只在给定目录中搜索。

webpack.config.js

module.exports = {
  //...
  resolve: {
    modules: ['node_modules'],
  },
};

如果你想添加一个优先于 node_modules/ 的搜索目录

webpack.config.js

const path = require('path');

module.exports = {
  //...
  resolve: {
    modules: [path.resolve(__dirname, 'src'), 'node_modules'],
  },
};

resolve.plugins

[Plugin]

一个应应用的额外解析插件列表。它允许诸如 DirectoryNamedWebpackPlugin 等插件。

webpack.config.js

module.exports = {
  //...
  resolve: {
    plugins: [new DirectoryNamedWebpackPlugin()],
  },
};

resolve.preferAbsolute

boolean

5.13.0+

解析时优先使用绝对路径,而不是 resolve.roots

webpack.config.js

module.exports = {
  //...
  resolve: {
    preferAbsolute: true,
  },
};

resolve.preferRelative

boolean

启用后,webpack 将优先将模块请求解析为相对请求,而不是使用 node_modules 目录中的模块。

webpack.config.js

module.exports = {
  //...
  resolve: {
    preferRelative: true,
  },
};

src/index.js

// let's say `src/logo.svg` exists
import logo1 from 'logo.svg'; // this is viable when `preferRelative` enabled
import logo2 from './logo.svg'; // otherwise you can only use relative path to resolve logo.svg

// `preferRelative` is enabled by default for `new URL()` case
const b = new URL('module/path', import.meta.url);
const a = new URL('./module/path', import.meta.url);

resolve.restrictions

[string, RegExp]

一个解析限制列表,用于限制请求可以解析的路径。

webpack.config.js

module.exports = {
  //...
  resolve: {
    restrictions: [/\.(sass|scss|css)$/],
  },
};

resolve.roots

[string]

一个目录列表,其中解析服务器相对 URL(以 '/' 开头)的请求,默认为 context 配置选项。在非 Windows 系统上,这些请求首先被解析为绝对路径。

webpack.config.js

const fixtures = path.resolve(__dirname, 'fixtures');
module.exports = {
  //...
  resolve: {
    roots: [__dirname, fixtures],
  },
};

resolve.symlinks

boolean = true

是否将符号链接解析为其符号链接位置。

启用后,符号链接资源将被解析为其真实路径,而不是其符号链接位置。请注意,当使用符号链接包的工具(如 npm link)时,这可能会导致模块解析失败。

webpack.config.js

module.exports = {
  //...
  resolve: {
    symlinks: true,
  },
};

resolve.unsafeCache

object boolean = true

启用激进但不安全的模块缓存。传入 true 将缓存所有内容。

webpack.config.js

module.exports = {
  //...
  resolve: {
    unsafeCache: true,
  },
};

当提供一个对象时,webpack 将其用作缓存。

例如,你可以提供一个 Proxy 对象而不是常规对象

webpack.config.js

// copied from discussion here https://github.com/webpack/webpack/discussions/18089
const realUnsafeCache = {};
const unsafeCacheHandler = {
  get(cache, key) {
    const cachedValue = cache[key];

    // make sure the file exists on disk
    if (cachedValue && !fs.existsSync(cachedValue.path)) {
      // and if it doesn't, evict that cache entry.
      delete cache[key];
      return undefined;
    }

    return cachedValue;
  },
};
const theProxiedCache = new Proxy(realUnsafeCache, unsafeCacheHandler);
module.exports = {
  //...
  resolve: {
    unsafeCache: theProxiedCache,
  },
};

resolve.useSyncFileSystemCalls

boolean

为解析器使用同步文件系统调用。

webpack.config.js

module.exports = {
  //...
  resolve: {
    useSyncFileSystemCalls: true,
  },
};

resolveLoader

object { modules [string] = ['node_modules'], extensions [string] = ['.js', '.json'], mainFields [string] = ['loader', 'main']}

这组选项与上面设置的 resolve 属性相同,但仅用于解析 webpack 的 loader 包。

webpack.config.js

module.exports = {
  //...
  resolveLoader: {
    modules: ['node_modules'],
    extensions: ['.js', '.json'],
    mainFields: ['loader', 'main'],
  },
};

17 贡献者

sokraskipjackSpaceK33zpksjcesebastiandeutschtbroadleybyzyknumb86jgravoisEugeneHlushkoAghassimyshovanikethsahachenxsanjamesgeorge007snitin315sapenlei