模块

这些选项决定了项目中的不同类型的模块将如何处理。

module.defaultRules

默认应用于模块的规则数组。

有关详细信息,请参阅源代码

module.exports = {
  module: {
    defaultRules: [
      '...', // you can use "..." to reference those rules applied by webpack by default
    ],
  },
};

从 webpack 5.87.0 开始,允许将包括 0""falsenullundefined 在内的假值传递给 module.defaultRules,以有条件地禁用特定规则。

module.exports = {
  module: {
    defaultRules: [
      false &&
        {
          // this rule will be disabled
        },
    ],
  },
};

module.generator

5.12.0+

可以通过 module.generator 在一个地方配置所有生成器的选项。

webpack.config.js

module.exports = {
  module: {
    generator: {
      asset: {
        // Generator options for asset modules

        // Indicates if this asset should be treated as binary. Set to 'false' to handle it as text instead. Available since webpack 5.93.0
        binary: false,

        // The options for data url generator.
        dataUrl: {
          // Asset encoding (defaults to "base64")
          // type: 'base64' | false
          encoding: 'base64',
          // Asset mimetype (getting from file extension by default).
          // type: string
          mimetype: 'image/png',
        },

        // Emit an output asset from this asset module. This can be set to 'false' to omit emitting e. g. for SSR.
        // type: boolean
        emit: true,

        // Customize filename for this asset module
        // type: string | ((pathData: PathData, assetInfo?: AssetInfo) => string)
        filename: 'static/[path][name][ext]',

        // Customize publicPath for asset modules, available since webpack 5.28.0
        // type: string | ((pathData: PathData, assetInfo?: AssetInfo) => string)
        publicPath: 'https://cdn/assets/',

        // Emit the asset in the specified folder relative to 'output.path', available since webpack 5.67.0
        // type: string | ((pathData: PathData, assetInfo?: AssetInfo) => string)
        outputPath: 'cdn-assets/',
      },
      'asset/inline': {
        // Generator options for asset/inline modules

        // Indicates if this asset should be treated as binary. Set to 'false' to handle it as text instead. Available since webpack 5.93.0
        binary: false,

        // The options for data url generator.
        dataUrl: {
          // Asset encoding (defaults to "base64")
          // type: 'base64' | false
          encoding: 'base64',
          // Asset mimetype (getting from file extension by default).
          // type: string
          mimetype: 'image/png',
        },
      },
      'asset/resource': {
        // Generator options for asset/resource modules

        // Indicates if this asset should be treated as binary. Set to 'false' to handle it as text instead. Available since webpack 5.93.0
        binary: false,

        // Emit an output asset from this asset module. This can be set to 'false' to omit emitting e. g. for SSR.
        // type: boolean
        emit: true,

        // Customize filename for this asset module
        // type: string | ((pathData: PathData, assetInfo?: AssetInfo) => string)
        filename: 'static/[path][name][ext]',

        // Customize publicPath for asset/resource modules, available since webpack 5.28.0
        // type: string | ((pathData: PathData, assetInfo?: AssetInfo) => string)
        publicPath: 'https://cdn/assets/',

        // Emit the asset in the specified folder relative to 'output.path', available since webpack 5.67.0
        // type: string | ((pathData: PathData, assetInfo?: AssetInfo) => string)
        outputPath: 'cdn-assets/',
      },
      javascript: {
        // No generator options are supported for this module type yet
      },
      'javascript/auto': {
        // ditto
      },
      'javascript/dynamic': {
        // ditto
      },
      'javascript/esm': {
        // ditto
      },
      css: {
        // Generator options for css modules

        // Avoid generating and loading a stylesheet and only embed exports from css into output javascript files.
        // type: boolean, available since webpack 5.90.0
        exportsOnly: true,

        // Customize how css export names are exported to javascript modules, such as keeping them as is, transforming them to camel case, etc.
        // type: 'as-is' | 'camel-case' | 'camel-case-only' | 'dashes' | 'dashes-only' | ((name: string) => string)
        // available since webpack 5.90.4
        exportsConvention: 'camel-case-only',
      },
      'css/auto': {
        // Generator options for css/auto modules

        // Avoid generating and loading a stylesheet and only embed exports from css into output javascript files.
        // type: boolean, available since webpack 5.90.0
        exportsOnly: true,

        // Customize how css export names are exported to javascript modules, such as keeping them as is, transforming them to camel case, etc.
        // type: 'as-is' | 'camel-case' | 'camel-case-only' | 'dashes' | 'dashes-only' | ((name: string) => string)
        // available since webpack 5.90.4
        exportsConvention: 'camel-case-only',

        // Customize the format of the local class names generated for css modules.
        // type: string, besides the substitutions at File-level and Module-level in https://webpack.js.cn/configuration/output/#template-strings, also include [uniqueName] and [local].
        // available since webpack 5.90.4
        localIdentName: '[uniqueName]-[id]-[local]',
      },
      'css/global': {
        // ditto
      },
      'css/module': {
        // ditto
      },
      json: {
        // Generator options for json modules
        // Use `JSON.parse` when the JSON string is longer than 20 characters.
        JSONParse: true,
      },
      // others…
    },
  },
};

module.parser

5.12.0+

module.generator 类似,你可以使用 module.parser 在一个地方配置所有解析器的选项。

webpack.config.js

module.exports = {
  module: {
    parser: {
      asset: {
        // Parser options for asset modules

        // The options for data url generator.
        dataUrl: {
          // Asset encoding (defaults to "base64")
          // type: 'base64' | false
          encoding: 'base64',
          // Asset mimetype (getting from file extension by default).
          // type: string
          mimetype: 'image/png',
        },

        // Emit an output asset from this asset module. This can be set to 'false' to omit emitting e. g. for SSR.
        // type: boolean
        emit: true,

        // Customize filename for this asset module
        // type: string | ((pathData: PathData, assetInfo?: AssetInfo) => string)
        filename: 'static/[path][name][ext]',

        // Customize publicPath for asset modules, available since webpack 5.28.0
        // type: string | ((pathData: PathData, assetInfo?: AssetInfo) => string)
        publicPath: 'https://cdn/assets/',

        // Emit the asset in the specified folder relative to 'output.path', available since webpack 5.67.0
        // type: string | ((pathData: PathData, assetInfo?: AssetInfo) => string)
        outputPath: 'cdn-assets/',
      },
      'asset/inline': {
        // No parser options are supported for this module type yet
      },
      'asset/resource': {
        // ditto
      },
      'asset/source': {
        // ditto
      },
      javascript: {
        // Parser options for javascript modules
        // e.g, enable parsing of require.ensure syntax
        requireEnsure: true,
        // Set the module to `'strict'` or `'non-strict'` mode. This can affect the module's behavior, as some behaviors differ between strict and non-strict modes.
        overrideStrict: 'non-strict',
      },
      'javascript/auto': {
        // ditto
      },
      'javascript/dynamic': {
        // ditto
      },
      'javascript/esm': {
        // ditto
      },
      css: {
        // Parser options for css modules

        // Enable/disable `@import` at-rules handling, available since webpack 5.97.0
        // type: boolean
        import: true,
        // Use ES modules named export for css exports, available since webpack 5.90.0
        // type: boolean
        namedExports: true,
        // Enable/disable url()/image-set()/src()/image() functions handling, available since webpack 5.97.0
        url: true,
      },
      'css/auto': {
        // ditto
      },
      'css/global': {
        // ditto
      },
      'css/module': {
        // ditto
      },
      // others…
    },
  },
};

module.parser.css

配置 CSS 解析器的选项。

module.exports = {
  module: {
    parser: {
      css: {
        // ...
        namedExports: true,
      },
    },
  },
};

module.parser.css.import

此选项启用 CSS 文件中 @import at-rule 的处理。当设置为 true 时,@import 语句将被处理,从而允许从其他 CSS 文件模块化地包含样式。

  • 类型:boolean

  • 可用版本:5.97.0+

  • 示例

    module.exports = {
      module: {
        parser: {
          css: {
            import: true,
          },
        },
      },
    };
    /* reset-styles.css */
    body {
      margin: 0;
      padding: 0;
    }
    /* styles.css */
    @import './reset-styles.css';
    
    body {
      background-color: red;
    }

module.parser.css.namedExports

此选项允许将 ES 模块的命名导出用于 CSS 导出。当设置为 true 时,CSS 模块将使用命名导出其类和样式。

  • 类型:boolean

  • 可用版本:5.90.0+

  • 示例

    module.exports = {
      module: {
        parser: {
          css: {
            namedExports: true,
          },
        },
      },
    };

当 CSS 模块的 namedExportsfalse 时,你可以使用各种导入方法检索 CSS 类。命名导出被重定向以改善开发者体验 (DX),从而促进从默认导出到命名导出的平滑过渡。

import * as styles from './styles.module.css';
import styles1 from './styles.module.css';
import { foo } from './styles.module.css';

console.log(styles.default.foo); // Access via styles.default
console.log(styles.foo); // Access directly from styles
console.log(styles1.foo); // Access via default import styles1
console.log(foo); // Direct named import

namedExports 被启用时(默认行为),你只能使用命名导出导入 CSS 类。

/* styles.css */
.header {
  color: blue;
}

.footer {
  color: green;
}
import { header, footer } from './styles.module.css';

通过启用 namedExports,你可以在 JavaScript 项目中采用更模块化、更易于维护的方式来管理 CSS,利用 ES 模块语法实现更清晰、更明确的导入。

module.parser.css.url

此选项启用或禁用 CSS 文件中 url()image-set()src()image() 等函数中 URL 的处理。启用后,这些 URL 将被 webpack 解析和处理。

  • 类型:boolean

  • 可用版本:5.97.0+

  • 示例

    module.exports = {
      module: {
        parser: {
          css: {
            url: true,
          },
        },
      },
    };
    /* styles.css */
    .background {
      background-image: url('./images/bg.jpg');
    }
    
    .icon {
      content: image('./icons/star.svg');
    }

module.parser.javascript

配置 JavaScript 解析器的选项。

module.exports = {
  module: {
    parser: {
      javascript: {
        // ...
        commonjsMagicComments: true,
      },
    },
  },
};

也可以在 Rule.parser 中配置这些选项以针对特定模块。

module.parser.javascript.commonjsMagicComments

启用 CommonJS 的魔法注释支持。

  • 类型:boolean

  • 可用版本:5.17.0+

  • 示例

    module.exports = {
      module: {
        parser: {
          javascript: {
            commonjsMagicComments: true,
          },
        },
      },
    };

请注意,目前仅支持 webpackIgnore 注释

const x = require(/* webpackIgnore: true */ 'x');

module.parser.javascript.dynamicImportFetchPriority

指定动态导入的全局 fetchPriority

  • 类型:'low' | 'high' | 'auto' | false

  • 可用版本:5.87.0+

  • 示例

    module.exports = {
      module: {
        parser: {
          javascript: {
            dynamicImportFetchPriority: 'high',
          },
        },
      },
    };

module.parser.javascript.dynamicImportMode

指定动态导入的全局模式。

  • 类型:'eager' | 'weak' | 'lazy' | 'lazy-once'

  • 可用版本:5.73.0+

  • 示例

    module.exports = {
      module: {
        parser: {
          javascript: {
            dynamicImportMode: 'lazy',
          },
        },
      },
    };

module.parser.javascript.dynamicImportPrefetch

指定动态导入的全局预取。

  • 类型:number | boolean

  • 可用版本:5.73.0+

  • 示例

    module.exports = {
      module: {
        parser: {
          javascript: {
            dynamicImportPrefetch: false,
          },
        },
      },
    };

module.parser.javascript.dynamicImportPreload

指定动态导入的全局预加载。

  • 类型:number | boolean

  • 可用版本:5.73.0+

  • 示例

    module.exports = {
      module: {
        parser: {
          javascript: {
            dynamicImportPreload: false,
          },
        },
      },
    };

module.parser.javascript.exportsPresence

指定 \"import ... from ...\"\"export ... from ...\" 中无效导出名称的行为。

  • 类型:'error' | 'warn' | 'auto' | false

  • 可用版本:5.62.0+

  • 示例

    module.exports = {
      module: {
        parser: {
          javascript: {
            exportsPresence: 'error',
          },
        },
      },
    };

module.parser.javascript.importExportsPresence

指定 \"import ... from ...\" 中无效导出名称的行为。

  • 类型:'error' | 'warn' | 'auto' | false

  • 可用版本:5.62.0+

  • 示例

    module.exports = {
      module: {
        parser: {
          javascript: {
            importExportsPresence: 'error',
          },
        },
      },
    };

module.parser.javascript.importMeta

启用或禁用对 import.meta 的评估。

  • 类型:boolean = true

  • 可用版本:5.68.0+

  • 示例

    module.exports = {
      module: {
        parser: {
          javascript: {
            importMeta: false,
          },
        },
      },
    };

module.parser.javascript.importMetaContext

启用/禁用对 import.meta.webpackContext 的评估。

  • 类型:boolean

  • 可用版本:5.70.0+

  • 示例

    module.exports = {
      module: {
        parser: {
          javascript: {
            importMetaContext: true,
          },
        },
      },
    };

module.parser.javascript.overrideStrict

将模块设置为 'strict''non-strict' 模式。这会影响模块的行为,因为某些行为在严格模式和非严格模式之间有所不同。

  • 类型:'strict' | 'non-strict'

  • 可用版本:5.93.0+

  • 示例

    module.exports = {
      module: {
        parser: {
          javascript: {
            overrideStrict: 'non-strict',
          },
        },
      },
    };

module.parser.javascript.reexportExportsPresence

指定 \"export ... from ...\" 中无效导出名称的行为。在 TypeScript 中重新导出类型时,从 \"export ... from ...\" 迁移到 \"export type ... from ...\" 期间禁用此功能可能会很有用。

  • 类型:'error' | 'warn' | 'auto' | false

  • 可用版本:5.62.0+

  • 示例

    module.exports = {
      module: {
        parser: {
          javascript: {
            reexportExportsPresence: 'error',
          },
        },
      },
    };

module.parser.javascript.url

启用 new URL() 语法的解析。

  • 类型:boolean = true | 'relative'

  • 示例

    module.exports = {
      module: {
        parser: {
          javascript: {
            url: false, // disable parsing of `new URL()` syntax
          },
        },
      },
    };

module.parser.javascript.url'relative' 值从 webpack 5.23.0 起可用。使用时,webpack 将为 new URL() 语法生成相对 URL,即结果 URL 中不包含基本 URL。

<!-- with 'relative' -->
<img src="c43188443804f1b1f534.svg" />

<!-- without 'relative' -->
<img src="file:///path/to/project/dist/c43188443804f1b1f534.svg" />
  1. 这对于 SSR(服务器端渲染)很有用,因为服务器可能不知道基本 URL(并且可以节省一些字节)。为了保持一致,客户端构建也必须使用它。
  2. 对于静态站点生成器、mini-css-plugin 和 html-plugin 等,通常也需要服务器端渲染。

module.parser.json

配置 JSON 解析器的选项。

module.exports = {
  module: {
    parser: {
      json: {
        // options
      },
    },
  },
};

module.parser.json.exportsDepth

被标记为 exportInfo 的 JSON 依赖的深度。默认情况下,在生产模式下它被设置为 Infinity,在开发模式下设置为 1

  • 类型:number
  • 可用版本:5.98.0+
  • 示例
module.exports = {
  module: {
    parser: {
      json: {
        // For example, for the following json
        // {
        //   "depth_1": {
        //     "depth_2": {
        //       "depth_3": "foo"
        //     }
        //   },
        //   "_depth_1": "bar"
        // }
        // when `exportsDepth: 1`, `depth_2` and `depth_3` will not be flagged as `exportInfo`.
        exportsDepth: 1,
      },
    },
  },
};

module.noParse

RegExp [RegExp] function(resource) string [string]

阻止 webpack 解析任何匹配给定正则表达式的文件。被忽略的文件不应包含对 importrequiredefine 或任何其他导入机制的调用。忽略大型库时,这可以提高构建性能。

noParse 还可以用于故意阻止所有 importrequiredefine 等调用的展开,适用于这些调用在运行时无法访问的情况。例如,当为 'browser' 目标构建项目并使用为浏览器和 Node.js 预构建的第三方库,并且该库需要 Node.js 内置模块(例如 require('os'))时。

webpack.config.js

module.exports = {
  //...
  module: {
    noParse: /jquery|lodash|src[\\/]vendor[\\/]somelib/,
  },
};
module.exports = {
  //...
  module: {
    noParse: (content) =>
      /jquery|lodash|src[\\/]vendor[\\/]somelib/.test(content),
  },
};

module.unsafeCache

boolean function (module)

缓存模块请求的解析。module.unsafeCache 有几个默认值:

  • 如果cache被禁用,则为 false
  • 如果cache被启用且模块似乎来自 node modules,则为 true,否则为 false

webpack.config.js

module.exports = {
  //...
  module: {
    unsafeCache: false,
  },
};

module.rules

(Rule | undefined | null | false | "" | 0 | "...")[]

一个规则数组,在创建模块时与请求匹配。这些规则可以修改模块的创建方式。它们可以向模块应用加载器,或修改解析器。

从 webpack 5.87.0 开始,可以使用诸如 falseundefinednull0 之类的假值来有条件地禁用规则。

Rule(规则)

对象

一条规则可以分为三个部分——条件、结果和嵌套规则。

规则条件

条件有两个输入值:

  1. 资源:被请求文件的绝对路径。它已根据resolve 规则解析。

  2. 发出者:请求资源的模块文件的绝对路径。它是导入的位置。

示例: 当我们在 app.jsimport './style.css' 时,资源是 /path/to/style.css,发出者是 /path/to/app.js

在规则中,testincludeexcluderesource 属性与资源匹配,而 issuer 属性与发出者匹配。

使用多个条件时,所有条件都必须匹配。

规则结果

规则结果仅在规则条件匹配时使用。

规则有两个输出值:

  1. 应用的加载器:应用于资源的加载器数组。
  2. 解析器选项:一个选项对象,用于为此模块创建解析器。

这些属性影响加载器:loaderoptionsuse

为了兼容性,还有这些属性:queryloaders

enforce 属性影响加载器类别。无论是普通加载器、前置加载器还是后置加载器。

parser 属性影响解析器选项。

嵌套规则

嵌套规则可以在 rulesoneOf 属性下指定。

这些规则仅在父规则条件匹配时才被评估。每个嵌套规则可以包含自己的条件。

评估顺序如下:

  1. 父规则
  2. rules
  3. oneOf

Rule.assert

一个Condition,允许你匹配依赖项的导入断言,并根据断言类型应用特定规则。

webpack.config.js

module.exports = {
  // ...
  module: {
    rules: [
      {
        // Handles imports with the assertion "assert { type: 'json' }"
        assert: { type: 'json' },
        loader: require.resolve('./loader-assert.js'),
      },
    ],
  },
};

index.js

import one from './pkg-1.json' assert { type: 'json' };

在此示例中,Rule.assert 用于将 loader-assert.js 应用于任何使用断言 assert { type: "json" } 导入的模块,确保 JSON 文件被正确处理。

Rule.compiler

一个Condition,允许你匹配子编译器的名称。

webpack.config.js

module.exports = {
  // ...
  name: 'compiler',
  module: {
    rules: [
      {
        test: /a\.js$/,
        compiler: 'compiler', // Matches the "compiler" name, loader will be applied
        use: './loader',
      },
      {
        test: /b\.js$/,
        compiler: 'other-compiler', // Does not match the "compiler" name, loader will NOT be applied
        use: './loader',
      },
    ],
  },
};

Rule.enforce

字符串

可能的值:'pre' | 'post'

指定加载器的类别。没有值表示普通加载器。

还有一个额外的类别“内联加载器”,它们是应用于导入/require 行内的加载器。

所有加载器按顺序进入两个阶段:

  1. Pitching 阶段:加载器上的 pitch 方法按 post, inline, normal, pre 的顺序调用。有关详细信息,请参阅Pitching Loader
  2. Normal 阶段:加载器上的 normal 方法按 pre, normal, inline, post 的顺序执行。模块的源代码转换发生在此阶段。

所有普通加载器都可以通过在请求中添加 ! 前缀来省略(覆盖)。

所有普通和前置加载器都可以通过在请求中添加 -! 前缀来省略(覆盖)。

所有普通、后置和前置加载器都可以通过在请求中添加 !! 前缀来省略(覆盖)。

// Disable normal loaders
import { a } from '!./file1.js';

// Disable preloaders and normal loaders
import { b } from '-!./file2.js';

// Disable all loaders
import { c } from '!!./file3.js';

内联加载器和 ! 前缀不应使用,因为它们是非标准的。它们可能被加载器生成的代码使用。

Rule.exclude

排除所有匹配这些条件的模块。如果你提供了 Rule.exclude 选项,则不能同时提供 Rule.resource。有关详细信息,请参阅Rule.resourceCondition.exclude

Rule.include

包含所有匹配这些条件的模块。如果你提供了 Rule.include 选项,则不能同时提供 Rule.resource。有关详细信息,请参阅Rule.resourceCondition.include

Rule.issuer

一个Condition,用于匹配发出请求的模块。在以下示例中,a.js 请求的 issuer 将是 index.js 文件的路径。

index.js

import A from './a.js';

此选项可用于将加载器应用于特定模块或一组模块的依赖项。

Rule.issuerLayer

允许按发出者的层级进行过滤/匹配。

webpack.config.js

module.exports = {
  // ...
  module: {
    rules: [
      {
        issuerLayer: 'other-layer',
      },
    ],
  },
};

Rule.layer

字符串

指定模块应放置的层。一组模块可以合并到一个层中,然后用于代码分割统计信息入口选项

webpack.config.js

module.exports = {
  // ...
  module: {
    rules: [
      {
        test: /module-layer-change/,
        layer: 'layer',
      },
    ],
  },
};

Rule.loader

Rule.loaderRule.use: [ { loader } ] 的快捷方式。有关详细信息,请参阅Rule.useUseEntry.loader

Rule.loaders

Rule.loadersRule.use 的别名。有关详细信息,请参阅Rule.use

Rule.mimetype

你可以使用 mimetype 将配置规则与数据 URI 匹配。

webpack.config.js

module.exports = {
  // ...
  module: {
    rules: [
      {
        mimetype: 'application/json',
        type: 'json',
      },
    ],
  },
};

application/jsontext/javascriptapplication/javascriptapplication/nodeapplication/wasm 已默认作为 mimetype 包含在内。

Rule.oneOf

一个Rules数组,当规则匹配时,只使用第一个匹配的规则。

webpack.config.js

module.exports = {
  //...
  module: {
    rules: [
      {
        test: /\.css$/,
        oneOf: [
          {
            resourceQuery: /inline/, // foo.css?inline
            type: 'asset/inline',
          },
          {
            resourceQuery: /external/, // foo.css?external
            type: 'asset/resource',
          },
        ],
      },
    ],
  },
};

Rule.options / Rule.query

Rule.optionsRule.queryRule.use: [ { options } ] 的快捷方式。有关详细信息,请参阅Rule.useUseEntry.options

Rule.parser

一个包含解析器选项的对象。所有应用的解析器选项都将被合并。

解析器可以检查这些选项并相应地禁用或重新配置自身。大多数默认插件按以下方式解释这些值:

  • 将选项设置为 false 会禁用解析器。
  • 将选项设置为 true 或保持 undefined 会启用解析器。

然而,解析器插件可能不仅仅接受布尔值。例如,内部的 NodeStuffPlugin 可以接受一个对象而不是 true,为特定规则添加额外选项。

示例(默认插件的解析器选项)

module.exports = {
  //...
  module: {
    rules: [
      {
        //...
        parser: {
          amd: false, // disable AMD
          commonjs: false, // disable CommonJS
          system: false, // disable SystemJS
          harmony: false, // disable ES2015 Harmony import/export
          requireInclude: false, // disable require.include
          requireEnsure: false, // disable require.ensure
          requireContext: false, // disable require.context
          browserify: false, // disable special handling of Browserify bundles
          requireJs: false, // disable requirejs.*
          node: false, // disable __dirname, __filename, module, require.extensions, require.main, etc.
          commonjsMagicComments: false, // disable magic comments support for CommonJS
          node: {}, // reconfigure node layer on module level
          worker: ['default from web-worker', '...'], // Customize the WebWorker handling for javascript files, "..." refers to the defaults.
        },
      },
    ],
  },
};

如果 Rule.typeasset,则 Rules.parser 选项可以是一个对象或一个函数,用于描述一个条件,即是否将文件内容编码为 Base64 或将其作为单独的文件输出到输出目录。

如果 Rule.typeassetasset/inline,则 Rule.generator 选项可以是一个对象,描述模块源的编码,或一个函数,用于通过自定义算法编码模块源。

有关更多信息和用例,请参阅Asset Modules 指南

Rule.parser.dataUrlCondition

object = { maxSize number = 8096 } function (source, { filename, module }) => boolean

如果模块源大小小于 maxSize,则模块将作为 Base64 编码的字符串注入到 bundle 中,否则模块文件将被输出到输出目录。

webpack.config.js

module.exports = {
  //...
  module: {
    rules: [
      {
        //...
        parser: {
          dataUrlCondition: {
            maxSize: 4 * 1024,
          },
        },
      },
    ],
  },
};

当给定一个函数时,返回 true 会告诉 webpack 将模块作为 Base64 编码的字符串注入到 bundle 中,否则模块文件将被输出到输出目录。

webpack.config.js

module.exports = {
  //...
  module: {
    rules: [
      {
        //...
        parser: {
          dataUrlCondition: (source, { filename, module }) => {
            const content = source.toString();
            return content.includes('some marker');
          },
        },
      },
    ],
  },
};

Rule.generator

Rule.generator.dataUrl

object = { encoding string = 'base64' | false, mimetype string = undefined | false } function (content, { filename, module }) => string

Rule.generator.dataUrl 用作对象时,你可以配置两个属性:

  • encoding:当设置为 'base64' 时,模块源将使用 Base64 算法编码。将 encoding 设置为 false 将禁用编码。
  • mimetype:数据 URI 的 mimetype。默认情况下从模块资源扩展名解析。

webpack.config.js

module.exports = {
  //...
  module: {
    rules: [
      {
        //...
        generator: {
          dataUrl: {
            encoding: 'base64',
            mimetype: 'mimetype/png',
          },
        },
      },
    ],
  },
};

当用作函数时,它会为每个模块执行,并且必须返回一个数据 URI 字符串。

module.exports = {
  //...
  module: {
    rules: [
      {
        //...
        generator: {
          dataUrl: (content) => {
            const svgToMiniDataURI = require('mini-svg-data-uri');
            if (typeof content !== 'string') {
              content = content.toString();
            }
            return svgToMiniDataURI(content);
          },
        },
      },
    ],
  },
};

Rule.generator.emit

选择不从Asset Modules写入资产,你可能希望在服务器端渲染场景中使用它。

  • 类型:boolean = true

  • 可用版本:5.25.0+

  • 示例

    module.exports = {
      // …
      module: {
        rules: [
          {
            test: /\.png$/i,
            type: 'asset/resource',
            generator: {
              emit: false,
            },
          },
        ],
      },
    };

Rule.generator.filename

output.assetModuleFilename 相同,但用于特定规则。它会覆盖 output.assetModuleFilename,并且仅适用于 assetasset/resource 模块类型。

webpack.config.js

module.exports = {
  //...
  output: {
    assetModuleFilename: 'images/[hash][ext][query]',
  },
  module: {
    rules: [
      {
        test: /\.png/,
        type: 'asset/resource',
      },
      {
        test: /\.html/,
        type: 'asset/resource',
        generator: {
          filename: 'static/[hash][ext]',
        },
      },
    ],
  },
};

Rule.generator.publicPath

为特定的 Asset Modules 自定义 publicPath

  • 类型:string | ((pathData: PathData, assetInfo?: AssetInfo) => string)
  • 可用版本:5.28.0+
module.exports = {
  //...
  output: {
    publicPath: 'static/',
  },
  module: {
    rules: [
      {
        test: /\.png$/i,
        type: 'asset/resource',
        generator: {
          publicPath: 'assets/',
        },
      },
    ],
  },
};

Rule.generator.outputPath

将资产输出到相对于 'output.path' 的指定文件夹中。仅当指定了自定义 'publicPath' 以匹配那里的文件夹结构时才需要此操作。

  • 类型:string | ((pathData: PathData, assetInfo?: AssetInfo) => string)
  • 可用版本:5.67.0+
module.exports = {
  //...
  output: {
    publicPath: 'static/',
  },
  module: {
    rules: [
      {
        test: /\.png$/i,
        type: 'asset/resource',
        generator: {
          publicPath: 'https://cdn/assets/',
          outputPath: 'cdn-assets/',
        },
      },
    ],
  },
};

Rule.resource

与资源匹配的Condition。详细信息请参阅规则条件

Rule.resourceQuery

与资源查询匹配的Condition。此选项用于测试请求字符串的查询部分(即从问号开始的部分)。如果你 import Foo from './foo.css?inline',以下条件将匹配:

webpack.config.js

module.exports = {
  //...
  module: {
    rules: [
      {
        test: /\.css$/,
        resourceQuery: /inline/,
        type: 'asset/inline',
      },
    ],
  },
};

Rule.parser.parse

function(input) => string | object

如果 Rule.type 设置为 'json',则 Rules.parser.parse 选项可以是一个函数,它实现自定义逻辑来解析模块源并将其转换为 JavaScript object。这对于导入 tomlyaml 和其他非 JSON 文件作为 JSON(无需特定加载器)可能很有用。

webpack.config.js

const toml = require('toml');

module.exports = {
  //...
  module: {
    rules: [
      {
        test: /\.toml/,
        type: 'json',
        parser: {
          parse: toml.parse,
        },
      },
    ],
  },
};

Rule.rules

一个Rules数组,当规则匹配时也会使用。

Rule.scheme

匹配使用的 schema,例如 datahttp

  • 类型:string | RegExp | ((value: string) => boolean) | RuleSetLogicalConditions | RuleSetCondition[]
  • 可用版本:5.38.0+

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        scheme: 'data',
        type: 'asset/resource',
      },
    ],
  },
};

Rule.sideEffects

布尔值

指示模块的哪些部分包含副作用。有关详细信息,请参阅Tree Shaking

Rule.test

包含所有通过测试断言的模块。如果你提供了 Rule.test 选项,则不能同时提供 Rule.resource。有关详细信息,请参阅Rule.resourceCondition

Rule.type

字符串

可能的值:'javascript/auto' | 'javascript/dynamic' | 'javascript/esm' | 'json' | 'webassembly/sync' | 'webassembly/async' | 'asset' | 'asset/source' | 'asset/resource' | 'asset/inline' | 'css/auto'

Rule.type 为匹配的模块设置类型。这可以防止默认规则及其默认导入行为的发生。例如,如果你想通过自定义加载器加载 .json 文件,你需要将 type 设置为 javascript/auto 以绕过 webpack 内置的 json 导入。

webpack.config.js

module.exports = {
  //...
  module: {
    rules: [
      //...
      {
        test: /\.json$/,
        type: 'javascript/auto',
        loader: 'custom-json-loader',
      },
    ],
  },
};

有关 asset* 类型的更多信息,请参阅Asset Modules 指南

css/auto

5.87.0+

在此处查看 css/auto 模块类型的用例。确保启用 experiments.css 以使用 css/auto

module.exports = {
  target: 'web',
  mode: 'development',
  experiments: {
    css: true,
  },
  module: {
    rules: [
      {
        test: /\.less$/,
        use: 'less-loader',
        type: 'css/auto',
      },
    ],
  },
};

Rule.use

[UseEntry] function(info)

从 webpack 5.87.0 开始,可以使用诸如 undefinednull 之类的假值来有条件地禁用特定的 use entry。

[UseEntry]

Rule.use 可以是应用于模块的UseEntry数组。每个条目指定一个要使用的加载器。

传递一个字符串(即 use: [ 'style-loader' ])是加载器属性的快捷方式(即 use: [ { loader: 'style-loader '} ])。

加载器可以通过传递多个加载器进行链式调用,它们将从右到左(从最后配置到最先配置)应用。

webpack.config.js

module.exports = {
  //...
  module: {
    rules: [
      {
        //...
        use: [
          'style-loader',
          {
            loader: 'css-loader',
            options: {
              importLoaders: 1,
            },
          },
          {
            loader: 'less-loader',
            options: {
              noIeCompat: true,
            },
          },
        ],
      },
    ],
  },
};

function(info)

Rule.use 也可以是一个函数,它接收描述正在加载模块的对象参数,并且必须返回一个非函数的 UseEntry 对象。这可以用于根据每个模块来更改加载器选项。

info 对象参数具有以下字段:

  • compiler:当前的 webpack 编译器(可以为 undefined)
  • issuer:导入正在加载模块的模块的路径
  • realResource:始终是正在加载模块的路径
  • resource:正在加载模块的路径,它通常等于 realResource,除非资源名称在请求字符串中通过 !=! 被覆盖。

返回值也可以使用与数组相同的快捷方式(即 use: [ 'style-loader' ])。

webpack.config.js

module.exports = {
  //...
  module: {
    rules: [
      {
        use: (info) => [
          {
            loader: 'custom-svg-loader',
          },
          {
            loader: 'svgo-loader',
            options: {
              plugins: [
                {
                  cleanupIDs: {
                    prefix: basename(info.resource),
                  },
                },
              ],
            },
          },
        ],
      },
    ],
  },
};

有关详细信息,请参阅UseEntry

Rule.resolve

解析可以在模块级别配置。有关所有可用选项,请参阅解析配置页面。所有应用的解析选项都会与更高级别的解析深度合并。

例如,假设我们在 ./src/index.js./src/footer/default.js./src/footer/overridden.js 中有一个入口文件,以演示模块级别的解析。

./src/index.js

import footer from 'footer';
console.log(footer);

./src/footer/default.js

export default 'default footer';

./src/footer/overridden.js

export default 'overridden footer';

webpack.js.org

module.exports = {
  resolve: {
    alias: {
      footer: './footer/default.js',
    },
  },
};

使用此配置创建 bundle 时,console.log(footer) 将输出 'default footer'。让我们为 .js 文件设置 Rule.resolve,并将 footer 别名为 overridden.js

webpack.js.org

module.exports = {
  resolve: {
    alias: {
      footer: './footer/default.js',
    },
  },
  module: {
    rules: [
      {
        resolve: {
          alias: {
            footer: './footer/overridden.js',
          },
        },
      },
    ],
  },
};

使用更新的配置创建 bundle 时,console.log(footer) 将输出 'overridden footer'。

resolve.fullySpecified

boolean = true

启用此功能时,当在 .mjs 文件或任何其他 .js 文件中 import 模块时(如果其最近的父级 package.json 文件包含值为 "module""type" 字段),你应该提供文件扩展名,否则 webpack 将因 Module not found 错误而编译失败。并且 webpack 不会解析在 resolve.mainFiles 中定义了文件名的目录,你必须自己指定文件名。

webpack.config.js

module.exports = {
  // ...
  module: {
    rules: [
      {
        test: /\.m?js$/,
        resolve: {
          fullySpecified: false, // disable the behaviour
        },
      },
    ],
  },
};

Rule.with

v5.92.0+

一个Condition,允许你根据 with 关键字提供的特定条件匹配导入,从而根据内容类型应用不同的规则。

webpack.config.js

module.exports = {
  // ...
  module: {
    rules: [
      {
        // Handles imports with the condition "with { type: 'json' }"
        with: { type: 'json' },
        loader: require.resolve('./loader-assert.js'),
      },
    ],
  },
};

index.js

import one from './pkg-1.json' with { type: 'json' };

在此示例中,Rule.with 用于将 loader-assert.js 应用于任何使用条件 with { type: "json" } 导入的模块。

Condition(条件)

条件可以是以下之一:

  • 字符串:输入必须以提供的字符串开头才能匹配。即绝对目录路径或文件的绝对路径。
  • 正则表达式:它与输入进行测试。
  • 函数:它以输入为参数被调用,并且必须返回一个真值才能匹配。
  • 条件数组:至少一个条件必须匹配。
  • 对象:所有属性都必须匹配。每个属性都有定义的行为。

{ and: [Condition] }:所有条件都必须匹配。

{ or: [Condition] }:任何条件都必须匹配。

{ not: [Condition] }:所有条件都不能匹配。

示例

const path = require('path');

module.exports = {
  //...
  module: {
    rules: [
      {
        test: /\.css$/,
        include: [
          // will include any paths relative to the current directory starting with `app/styles`
          // e.g. `app/styles.css`, `app/styles/styles.css`, `app/stylesheet.css`
          path.resolve(__dirname, 'app/styles'),
          // add an extra slash to only include the content of the directory `vendor/styles/`
          path.join(__dirname, 'vendor/styles/'),
        ],
      },
    ],
  },
};

UseEntry

object function(info)

对象

它必须有一个字符串类型的 loader 属性。它相对于配置的context使用加载器解析选项(resolveLoader)进行解析。

它可以有一个字符串或对象类型的 options 属性。此值将传递给加载器,加载器应将其解释为加载器选项。

为了兼容性,也可以使用 query 属性,它是 options 属性的别名。请改用 options 属性。

请注意,webpack 需要从资源和所有加载器(包括选项)生成唯一的模块标识符。它尝试通过对选项对象进行 JSON.stringify 来实现。这在 99.9% 的情况下是没问题的,但如果你对资源应用相同加载器但选项不同,且选项的字符串化值相同,则可能不唯一。

如果选项对象无法字符串化(即循环 JSON),它也会中断。因此,你可以在选项对象中有一个 ident 属性,用作唯一标识符。

webpack.config.js

module.exports = {
  //...
  module: {
    rules: [
      {
        loader: 'css-loader',
        options: {
          modules: true,
        },
      },
    ],
  },
};

function(info)

UseEntry 也可以是一个函数,它接收描述正在加载模块的对象参数,并且必须返回一个非函数的 UseEntry 对象。这可以用于根据每个模块来更改加载器选项。

info 对象参数具有以下字段:

  • compiler:当前的 webpack 编译器(可以为 undefined)
  • issuer:导入正在加载模块的模块的路径
  • realResource:始终是正在加载模块的路径
  • resource:正在加载模块的路径,它通常等于 realResource,除非资源名称在请求字符串中通过 !=! 被覆盖。

webpack.config.js

module.exports = {
  //...
  module: {
    rules: [
      {
        test: /\.svg$/,
        type: 'asset',
        use: (info) => ({
          loader: 'svgo-loader',
          options: {
            plugins: [
              {
                cleanupIDs: { prefix: basename(info.resource) },
              },
            ],
          },
        }),
      },
    ],
  },
};

模块上下文

这些选项描述了遇到动态依赖项时创建的上下文的默认设置。

unknown 动态依赖项的示例:require

expr 动态依赖项的示例:require(expr)

wrapped 动态依赖项的示例:require('./templates/' + expr)

以下是可用选项及其默认值

webpack.config.js

module.exports = {
  //...
  module: {
    exprContextCritical: true,
    exprContextRecursive: true,
    exprContextRegExp: false,
    exprContextRequest: '.',
    unknownContextCritical: true,
    unknownContextRecursive: true,
    unknownContextRegExp: false,
    unknownContextRequest: '.',
    wrappedContextCritical: false,
    wrappedContextRecursive: true,
    wrappedContextRegExp: /.*/,
    strictExportPresence: false,
  },
};

几个用例:

  • 警告动态依赖项:wrappedContextCritical: true
  • require(expr) 应包含整个目录:exprContextRegExp: /^\.\//
  • require('./templates/' + expr) 默认不应包含子目录:wrappedContextRecursive: false
  • strictExportPresence 使缺失的导出变为错误而不是警告
  • 为部分动态依赖项设置内部正则表达式:wrappedContextRegExp: /\\.\\*/

22 贡献者

sokraskipjackjouni-kantolajhnnsdylanonelsonbyzykpnevaresfadysamirsadeknerdkid93EugeneHlushkosuperburritolukasgeiterskovysmelukovopl-Mistyyyyanshumanvchenxsansnitin315vabushkevichahabhgkhai-x