Модуль
Эти параметры определяют, как будут обрабатываться различные типы модулей в проекте.
module.defaultRules
Массив правил, применяемых по умолчанию для модулей.
См. исходный код для получения подробностей.
module.exports = {
module: {
defaultRules: [
'...', // you can use "..." to reference those rules applied by webpack by default
],
},
}; Начиная с webpack 5.87.0, ложные значения, включая 0, "", false, null и undefined, разрешены для передачи в 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.org/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
},
// 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
// Use ES modules named export for css exports, available since webpack 5.90.0
// type: boolean
namedExports: true,
},
'css/auto': {
// ditto
},
'css/global': {
// ditto
},
'css/module': {
// ditto
},
// others…
},
},
}; module.parser.css.namedExports
Этот параметр включает использование именованных экспортов ES модулей для экспорта CSS. При установке в значение true, модуль CSS будет экспортировать свои классы и стили с использованием именованных экспортов.
-
Тип:
boolean -
Доступно: 5.90.0+
-
Пример:
module.exports = { module: { parser: { css: { namedExports: true, }, }, }, };
Когда namedExports установлено в false для модулей CSS, вы можете получать классы 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, вы примете более модульный и поддерживаемый подход к управлению CSS в JavaScript-проектах, используя синтаксис ES модулей для более явных и понятных импортов.
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 ...\". Это может быть полезно для отключения во время миграции от \"export ... from ...\" к \"export type ... from ...\", когда переэкспортируются типы в TypeScript.
-
Тип:
'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 }, }, }, };
Значение 'relative' для module.parser.javascript.url доступно с webpack 5.23.0. При использовании webpack сгенерирует относительные URL для синтаксиса new URL(), т.е. базовый URL не включен в результирующий URL:
<!-- with 'relative' --> <img src="c43188443804f1b1f534.svg" /> <!-- without 'relative' --> <img src="file:///path/to/project/dist/c43188443804f1b1f534.svg" />
- Это полезно для SSR (рендеринг на стороне сервера), когда базовый URL не известен серверу (и это экономит несколько байтов). Для идентичности необходимо также использовать его для сборки на клиенте.
- Также для статических генераторов сайтов, mini-css-plugin и html-plugin и т.д., где часто необходим рендеринг на стороне сервера.
module.noParse
RegExp [RegExp] function(resource) string [string]
Запретить webpack парсить любые файлы, соответствующие заданному(ым) регулярному(ым) выражению(ям). Пропущенные файлы не должны иметь вызовы import, require, define или любого другого механизма импорта. Это может повысить производительность сборки при игнорировании больших библиотек.
noParse также может использоваться для преднамеренного предотвращения расширения всех import, require, define и т.п. вызовов в случаях, когда эти вызовы недостижимы во время выполнения. Например, при сборке проекта для '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:
-
falseеслиcacheотключен. -
trueеслиcacheвключен, и модуль, кажется, из папки node_modules,falseв противном случае.
webpack.config.js
module.exports = {
//...
module: {
unsafeCache: false,
},
}; module.rules
(Rule | undefined | null | false | "" | 0 | "...")[]
Массив правил, которые сопоставляются с запросами при создании модулей. Эти правила могут изменять способ создания модуля. Они могут применять загрузчики к модулю или изменять парсер.
Начиная с webpack 5.87.0, ложные значения, такие как false, undefined, null и 0, могут использоваться для условного отключения правила.
Правило
object
Правило может быть разделено на три части — Условия, Результаты и вложенные Правила.
Условия Правила
Для условий есть два входных значения:
-
Ресурс: Абсолютный путь к запрошенному файлу. Он уже разрешен в соответствии с
resolveправилами. -
Издатель: Абсолютный путь к файлу модуля, который запросил ресурс. Это расположение импорта.
Пример: Когда мы import './style.css' в app.js, ресурсом является /path/to/style.css, а издателем является /path/to/app.js.
В правиле свойства test, include, exclude и resource сопоставляются с ресурсом, а свойство issuer сопоставляется с издателем.
При использовании нескольких условий, все условия должны соответствовать.
Результаты Правила
Результаты правила используются только в случае совпадения условия правила.
Есть два выходных значения правила:
- Применённые загрузчики: Массив загрузчиков, применённых к ресурсу.
- Параметры парсера: Объект параметров, который должен использоваться для создания парсера для этого модуля.
Эти свойства влияют на загрузчики: loader, options, use.
Для совместимости также эти свойства: query, loaders.
Свойство enforce влияет на категорию загрузчика. Будет ли это обычный, предварительный или последующий загрузчик.
Свойство parser влияет на параметры парсера.
Вложенные правила
Вложенные правила могут быть указаны в свойствах rules и oneOf.
Эти правила оцениваются только в случае совпадения условия родительского правила. Каждое вложенное правило может содержать свои собственные условия.
Порядок оценки следующий:
Rule.assert
A Condition that allows you to match the import assertion of a dependency and apply specific rules based on the assertion type.
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' }; In this example, Rule.assert is used to apply loader-assert.js to any module imported with the assertion assert { type: "json" }, ensuring that JSON files are processed correctly.
Правило.компилятор
A Condition that allows you to match the child compiler name.
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',
},
],
},
}; Правило.enforce
string
Possible values: 'pre' | 'post'
Specifies the category of the loader. No value means normal loader.
There is also an additional category "inlined loader" which are loaders applied inline of the import/require.
There are two phases that all loaders enter one after the other:
-
Pitching phase: the pitch method on loaders is called in the order
post, inline, normal, pre. See Pitching Loader for details. -
Normal phase: the normal method on loaders is executed in the order
pre, normal, inline, post. Transformation on the source code of a module happens in this phase.
All normal loaders can be omitted (overridden) by prefixing ! in the request.
All normal and pre loaders can be omitted (overridden) by prefixing -! in the request.
All normal, post and pre loaders can be omitted (overridden) by prefixing !! in the request.
// 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'; Inline loaders and ! prefixes should not be used as they are non-standard. They may be used by loader generated code.
Правило.исключить
Exclude all modules matching any of these conditions. If you supply a Rule.exclude option, you cannot also supply a Rule.resource. See Rule.resource and Condition.exclude for details.
Правило.включить
Include all modules matching any of these conditions. If you supply a Rule.include option, you cannot also supply a Rule.resource. See Rule.resource and Condition.include for details.
Правило.источник
A Condition to match against the module that issued the request. In the following example, the issuer for the a.js request would be the path to the index.js file.
index.js
import A from './a.js';
This option can be used to apply loaders to the dependencies of a specific module or set of modules.
Правило.уровень_источника
Allows to filter/match by layer of the issuer.
webpack.config.js
module.exports = {
// ...
module: {
rules: [
{
issuerLayer: 'other-layer',
},
],
},
}; Правило.уровень
string
Specify the layer in which the module should be placed in. A group of modules could be united in one layer which could then be used in split chunks, stats or entry options.
webpack.config.js
module.exports = {
// ...
module: {
rules: [
{
test: /module-layer-change/,
layer: 'layer',
},
],
},
}; Правило.загрузчик
Rule.loader is a shortcut to Rule.use: [ { loader } ]. See Rule.use and UseEntry.loader for details.
Правило.загрузчики
Rule.loaders is an alias to Rule.use. See Rule.use for details.
Правило.тип_mime
You can match config rules to data uri with mimetype.
webpack.config.js
module.exports = {
// ...
module: {
rules: [
{
mimetype: 'application/json',
type: 'json',
},
],
},
}; application/json, text/javascript, application/javascript, application/node and application/wasm are already included by default as mimetype.
Правило.один_из
An array of Rules from which only the first matching Rule is used when the Rule matches.
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 and Rule.query are shortcuts to Rule.use: [ { options } ]. See Rule.use and UseEntry.options for details.
Правило.парсер
An object with parser options. All applied parser options are merged.
Parsers may inspect these options and disable or reconfigure themselves accordingly. Most of the default plugins interpret the values as follows:
- Setting the option to
falsedisables the parser. - Setting the option to
trueor leaving itundefinedenables the parser.
However, parser plugins may accept more than only a boolean. For example, the internal NodeStuffPlugin can accept an object instead of true to add additional options for a particular Rule.
Examples (parser options by the default plugins):
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.
},
},
],
},
}; If Rule.type is an asset then Rules.parser option may be an object or a function that describes a condition whether to encode file contents to Base64 or emit it as a separate file into the output directory.
If Rule.type is an asset or asset/inline then Rule.generator option may be an object that describes the encoding of the module source or a function that encodes module's source by a custom algorithm.
See Asset Modules guide for additional information and use cases.
Правило.парсер.условие_dataUrl
object = { maxSize number = 8096 } function (source, { filename, module }) => boolean
If a module source size is less than maxSize then module will be injected into the bundle as a Base64-encoded string, otherwise module file will be emitted into the output directory.
webpack.config.js
module.exports = {
//...
module: {
rules: [
{
//...
parser: {
dataUrlCondition: {
maxSize: 4 * 1024,
},
},
},
],
},
}; When a function is given, returning true tells webpack to inject the module into the bundle as Base64-encoded string, otherwise module file will be emitted into the output directory.
webpack.config.js
module.exports = {
//...
module: {
rules: [
{
//...
parser: {
dataUrlCondition: (source, { filename, module }) => {
const content = source.toString();
return content.includes('some marker');
},
},
},
],
},
}; Правило.генератор
Правило.генератор.dataUrl
object = { encoding string = 'base64' | false, mimetype string = undefined | false } function (content, { filename, module }) => string
When Rule.generator.dataUrl is used as an object, you can configure two properties:
- encoding: When set to
'base64', module source will be encoded using Base64 algorithm. Settingencodingto false will disable encoding. - mimetype: A mimetype for data URI. Resolves from module resource extension by default.
webpack.config.js
module.exports = {
//...
module: {
rules: [
{
//...
generator: {
dataUrl: {
encoding: 'base64',
mimetype: 'mimetype/png',
},
},
},
],
},
}; When used a a function, it executes for every module and must return a data URI string.
module.exports = {
//...
module: {
rules: [
{
//...
generator: {
dataUrl: (content) => {
const svgToMiniDataURI = require('mini-svg-data-uri');
if (typeof content !== 'string') {
content = content.toString();
}
return svgToMiniDataURI(content);
},
},
},
],
},
}; Правило.генератор.создать
Opt out of writing assets from Asset Modules, you might want to use it in Server side rendering cases.
-
Тип:
boolean = true -
Доступно: 5.25.0+
-
Пример:
module.exports = { // … module: { rules: [ { test: /\.png$/i, type: 'asset/resource', generator: { emit: false, }, }, ], }, };
Правило.генератор.имя_файла
The same as output.assetModuleFilename but for specific rule. Overrides output.assetModuleFilename and works only with asset and asset/resource module types.
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]',
},
},
],
},
}; Правило.генератор.publicPath
Customize publicPath for specific Asset Modules.
- Тип:
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/',
},
},
],
},
}; Правило.генератор.outputPath
Emit the asset in the specified folder relative to 'output.path'. This should only be needed when custom 'publicPath' is specified to match the folder structure there.
- Тип:
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/',
},
},
],
},
}; Правило.ресурс
A Condition matched with the resource. See details in Rule conditions.
Правило.запрос_ресурса
A Condition matched with the resource query. This option is used to test against the query section of a request string (i.e. from the question mark onwards). If you were to import Foo from './foo.css?inline', the following condition would match:
webpack.config.js
module.exports = {
//...
module: {
rules: [
{
test: /\.css$/,
resourceQuery: /inline/,
type: 'asset/inline',
},
],
},
}; Правило.парсер.разбор
function(input) => string | object
If Rule.type is set to 'json' then Rules.parser.parse option may be a function that implements custom logic to parse module's source and convert it to a JavaScript object. It may be useful to import toml, yaml and other non-JSON files as JSON, without specific loaders:
webpack.config.js
const toml = require('toml');
module.exports = {
//...
module: {
rules: [
{
test: /\.toml/,
type: 'json',
parser: {
parse: toml.parse,
},
},
],
},
}; Правило.правила
An array of Rules that is also used when the Rule matches.
Правило.схема
Match the used schema, e.g., data, http.
- Тип:
string | RegExp | ((value: string) => boolean) | RuleSetLogicalConditions | RuleSetCondition[] - Доступно: 5.38.0+
webpack.config.js
module.exports = {
module: {
rules: [
{
scheme: 'data',
type: 'asset/resource',
},
],
},
}; Правило.побочные_эффекты
bool
Indicate what parts of the module contain side effects. See Tree Shaking for details.
Правило.тест
Include all modules that pass test assertion. If you supply a Rule.test option, you cannot also supply a Rule.resource. See Rule.resource and Condition for details.
Правило.тип
string
Possible values: 'javascript/auto' | 'javascript/dynamic' | 'javascript/esm' | 'json' | 'webassembly/sync' | 'webassembly/async' | 'asset' | 'asset/source' | 'asset/resource' | 'asset/inline' | 'css/auto'
Rule.type sets the type for a matching module. This prevents defaultRules and their default importing behaviors from occurring. For example, if you want to load a .json file through a custom loader, you'd need to set the type to javascript/auto to bypass webpack's built-in json importing.
webpack.config.js
module.exports = {
//...
module: {
rules: [
//...
{
test: /\.json$/,
type: 'javascript/auto',
loader: 'custom-json-loader',
},
],
},
}; See Asset Modules guide for more about
asset*type.
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',
},
],
},
}; Правило.use
[UseEntry] function(info)
Начиная с webpack 5.87.0, ложные значения, такие как undefined null, могут использоваться для условной отмены конкретного входа use.
[UseEntry]
Rule.use может быть массивом UseEntry, которые применяются к модулям. Каждый элемент указывает загрузчик, который следует использовать.
Передача строки (например, use: [ 'style-loader' ]) — это сокращение для свойства 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 (может быть неопределённым) -
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 для получения дополнительных сведений.
Правило.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',
},
},
}; При создании сборки с этой конфигурацией console.log(footer) выведет «default footer». Давайте зададим Rule.resolve для файлов .js, и псевдоним footer к overridden.js.
webpack.js.org
module.exports = {
resolve: {
alias: {
footer: './footer/default.js',
},
},
module: {
rules: [
{
resolve: {
alias: {
footer: './footer/overridden.js',
},
},
},
],
},
}; При создании сборки с обновлённой конфигурацией console.log(footer) выведет «overridden footer».
resolve.fullySpecified
boolean = true
При включении вы должны указать расширение файла при import модуля в файлах .mjs или любых других файлах .js, если ближайший родительский файл package.json содержит поле "type" со значением "module", в противном случае webpack завершит компиляцию с ошибкой Module not found. И webpack не будет разрешать каталоги с именами файлов, определёнными в resolve.mainFiles, вы должны самостоятельно указать имя файла.
webpack.config.js
module.exports = {
// ...
module: {
rules: [
{
test: /\.m?js$/,
resolve: {
fullySpecified: false, // disable the behaviour
},
},
],
},
}; Правило.with
v5.92.0+A 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" }.
Условие
Условия могут быть следующими:
- Строка: для соответствия вход должен начинаться с указанной строки. Например, абсолютный путь к каталогу или абсолютный путь к файлу.
- RegExp: используется для проверки входных данных.
- Функция: вызывается с входными данными и должна возвращать истинное значение для соответствия.
- Массив условий: для соответствия должно выполняться как минимум одно из условий.
- Объект: все свойства должны соответствовать. Каждое свойство имеет определённое поведение.
{ 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)
object
Он должен иметь свойство loader, которое является строкой. Оно разрешается относительно конфигурации context с параметрами разрешения загрузчика (resolveLoader).
Он может иметь свойство options, которое является строкой или объектом. Это значение передаётся загрузчику, который должен интерпретировать его как параметры загрузчика.
Для совместимости также возможно свойство query, которое является псевдонимом для свойства options. Используйте свойство options вместо него.
Обратите внимание, что webpack должен сгенерировать уникальный идентификатор модуля из ресурса и всех загрузчиков, включая параметры. Он пытается сделать это в 99,9% случаев, но может не быть уникальным, если вы применяете одни и те же загрузчики с разными параметрами к ресурсу, и параметры имеют одинаковые строковые значения.
Это также не работает, если объект параметров нельзя сериализовать в строку (например, циклический JSON). Из-за этого вы можете иметь свойство ident в объекте параметров, которое используется в качестве уникального идентификатора.
webpack.config.js
module.exports = {
//...
module: {
rules: [
{
loader: 'css-loader',
options: {
modules: true,
},
},
],
},
}; function(info)
UseEntry также может быть функцией, которая получает объект, описывающий загружаемый модуль, и должна возвращать не-функциональный объект UseEntry. Это можно использовать для изменения параметров загрузчика в зависимости от каждого модуля.
Параметр объекта info имеет следующие поля:
-
compiler: Текущий компилятор webpack (может быть неопределённым) -
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: /\\.\\*/
© JS Foundation and other contributors
Licensed under the Creative Commons Attribution License 4.0.
https://webpack.js.org/configuration/module