Module
이 옵션은 프로젝트 내에서 다른 유형의 모듈을 처리하는 방법을 결정합니다.
module.defaultRules
모듈에 기본적으로 적용되는 규칙의 배열입니다.
자세한 내용은 소스 코드를 참고하세요.
export default {
module: {
defaultRules: [
"...", // "..."를 사용하여 기본적으로 webpack에 의해 적용되는 규칙을 참조할 수 있습니다.
],
},
};Webpack 5.87.0부터 0, "", false, null 및 undefined를 포함한 falsy 값을 module.defaultRules로 전달하여 특정 규칙을 조건부로 비활성화할 수 있습니다.
export default {
module: {
defaultRules: [
false &&
{
// 이 규칙은 비활성화됩니다.
},
],
},
};module.generator
5.12.0+module.generator를 사용하여 한 곳에서 모든 제너레이터의 옵션을 설정할 수 있습니다.
webpack.config.js
export default {
module: {
generator: {
asset: {
// asset 모듈 제너레이터 옵션
// 이 애셋을 바이너리로 처리해야 하는지 여부를 나타냅니다. 대신 텍스트로 처리하려면 'false'로 설정합니다. webpack 5.93.0부터 사용 가능합니다.
binary: false,
// 데이터 URL 제너레이터 옵션입니다.
dataUrl: {
// 애셋 인코딩(기본값은 "base64")
// type: 'base64' | false
encoding: "base64",
// 애셋 Mimetype (기본적으로 파일 확장자에서 가져옵니다).
// type: string
mimetype: "image/png",
},
// 이 애셋 모듈에서 출력 애셋을 내보냅니다. 예를 들어 SSR의 경우 내보내기를 생략하려면 'false'로 설정할 수 있습니다.
// type: boolean
emit: true,
// 이 애셋 모듈의 파일 이름을 사용자 정의합니다.
// type: string | ((pathData: PathData, assetInfo?: AssetInfo) => string)
filename: "static/[path][name][ext]",
// asset 모듈을 위한 publicPath 사용자 정의. webpack 5.28.0 이후로 사용 가능.
// type: string | ((pathData: PathData, assetInfo?: AssetInfo) => string)
publicPath: "https://cdn/assets/",
// Webpack 5.67.0부터 사용 가능한 'output.path'를 기준으로 지정된 폴더의 애셋을 내보냅니다.
// type: string | ((pathData: PathData, assetInfo?: AssetInfo) => string)
outputPath: "cdn-assets/",
},
"asset/inline": {
// asset/inline 모듈 제너레이터 옵션
// 이 애셋을 바이너리로 처리해야 하는지 여부를 나타냅니다. 대신 텍스트로 처리하려면 'false'로 설정합니다. webpack 5.93.0부터 사용 가능합니다.
binary: false,
// 데이터 URL 제너레이터 옵션
dataUrl: {
// 애셋 인코딩(기본값은 "base64")
// type: 'base64' | false
encoding: "base64",
// 애셋 Mimetype (기본적으로 파일 확장자에서 가져옵니다).
// type: string
mimetype: "image/png",
},
},
"asset/resource": {
// asset/resource 모듈 제너레이터 옵션
// 이 애셋을 바이너리로 처리해야 하는지 여부를 나타냅니다. 대신 텍스트로 처리하려면 'false'로 설정합니다. webpack 5.93.0부터 사용 가능합니다.
binary: false,
// 이 애셋 모듈에서 출력 애셋을 내보냅니다. 예를 들어 SSR의 경우 내보내기를 생략하려면 'false'로 설정할 수 있습니다.
// type: boolean
emit: true,
// 이 애셋 모듈의 파일 이름을 사용자 정의합니다.
// type: string | ((pathData: PathData, assetInfo?: AssetInfo) => string)
filename: "static/[path][name][ext]",
// asset/resource 모듈을 위한 publicPath 사용자 정의. webpack 5.28.0 이후로 사용 가능.
// type: string | ((pathData: PathData, assetInfo?: AssetInfo) => string)
publicPath: "https://cdn/assets/",
// Webpack 5.67.0부터 사용 가능한 'output.path'를 기준으로 지정된 폴더의 애셋을 내보냅니다.
// type: string | ((pathData: PathData, assetInfo?: AssetInfo) => string)
outputPath: "cdn-assets/",
},
"asset/bytes": {
// 아직 이 모듈 유형에 대해 지원되는 제너레이터 옵션이 없습니다.
},
javascript: {
// 이 모듈 유형에는 아직 제너레이터 옵션이 지원되지 않습니다.
},
"javascript/auto": {
// 위와 동일
},
"javascript/dynamic": {
// 위와 동일
},
"javascript/esm": {
// 위와 동일
},
css: {
// CSS 모듈용 제너레이터 옵션
// 스타일시트를 생성하고 로드하는 것을 피하고 출력 자바스크립트 파일에 css의 내보내기만 포함합니다.
// type: boolean, webpack 5.90.0부터 사용 가능합니다.
exportsOnly: true,
},
"css/auto": {
// CSS/자동 모듈 생성용 옵션
// 스타일시트를 생성하고 로드하는 것을 피하고 출력 자바스크립트 파일에 css의 내보내기만 포함합니다.
// type: boolean, webpack 5.90.0부터 사용 가능합니다.
exportsOnly: true,
// css export 이름을 javascript module로 내보내는 방식을 사용자 정의합니다. 예를 들어 현재 형태를 유지하거나 camel case로 변환할 수 있습니다.
// type: 'as-is' | 'camel-case' | 'camel-case-only' | 'dashes' | 'dashes-only' | ((name: string) => string | string[])
// webpack 5.91.0부터 사용 가능하며, 함수 형식은 webpack 5.107.0부터 string[]를 반환할 수 있습니다.
exportsConvention: "camel-case-only",
// CSS 모듈에 대해 생성된 로컬 클래스 이름의 형식을 사용자 정의합니다.
// type: string, https://webpack.js.org/configuration/output/#template-strings의 파일 수준 및 모듈 수준 대체 외에도 [uniqueName] 및 [local]도 포함됩니다.
// webpack 5.91.0부터 사용 가능합니다.
// webpack 5.108.0부터 여기서 [hash]는 로컬 식별자 해시로 해석됩니다. 모듈 해시를 위해서는 [modulehash]를 사용하세요. 인라인 다이제스트/길이 형식도 지원됩니다. 예: [hash:base64:8].
// 여기서 [hash]와 [fullhash]는 compilation hash가 아니라 로컬 식별자 해시입니다. 즉, `localIdentHashSalt`, `output.uniqueName`, `context`에 대한 상대 리소스 경로 및 로컬 이름의 해시입니다.
// 이는 결정론적이므로, 해당 값들을 공유하고 다른 모든 placeholder(예: [id])를 같은 방식으로 해석하는 빌드는 동일한 class name을 생성합니다(예: SSR용 web 및 node 빌드).
localIdentName: "[uniqueName]-[id]-[local]",
},
"css/global": {
// 위와 동일
},
"css/module": {
// 위와 동일
},
json: {
// JSON 모듈에 대한 생성기 옵션
// JSON 문자열이 20자를 넘는 경우 `JSON.parse`를 사용합니다.
// type: boolean, 기본값 true
JSONParse: true,
},
html: {
// html 모듈에 대한 생성기 옵션, `experiments.html` 필요, webpack 5.107.0부터 사용 가능
// 파싱되고 URL이 재작성된 HTML을 독립 실행형 .html 출력 파일로 생성합니다.
// type: boolean | 'inline'
extract: true,
},
// 그외 다른 옵션들…
},
},
};Multiple aliases via exportsConvention
5.107.0+
exportsConvention이 함수인 경우 string 또는 string[]를 반환할 수 있습니다. 배열을 반환하면 배열에 포함된 모든 이름으로 local class를 export하며, 이는 css-loader의 동작과 일치합니다. 같은 class를 여러 alias로 노출하고 싶지만 두 개의 rule을 작성하고 싶지 않을 때 유용합니다.
webpack.config.js
export default {
experiments: { css: true },
module: {
generator: {
"css/module": {
// 각 class를 원래 이름과 대문자 alias 두 가지로 모두 노출합니다.
exportsConvention: (name) => [name, name.toUpperCase()],
},
},
},
};import styles from "./button.module.css";
console.log(styles.btn); // 해시된 class
console.log(styles.BTN); // 같은 해시된 class의 대문자 aliasmodule.generator.css.exportsOnly
boolean
스타일시트 생성 및 로드를 건너뛰고 CSS 모듈의 내보내기(로컬 클래스 이름에서 생성된 이름으로의 매핑)만 JavaScript 출력에 포함합니다. 이는 스타일이 클라이언트 빌드에서 제공되고 서버는 이름만 필요한 서버 사이드 빌드에 적합합니다.
- 기본값:
document가 있는 타겟의 경우false, 없는 타겟(node등)의 경우true이므로 서버 빌드에서는 별도 설정 없이 동작합니다.
module.generator.css.esModule
boolean = true
CSS 모듈의 내보내기를 ES 모듈 구문으로 생성하여 트리 쉐이킹과 연결이 가능하도록 합니다. CommonJS 내보내기를 출력하려면 false로 설정하세요.
module.generator.html.extract
5.107.0+boolean = true 'inline'
HTML 모듈이 파싱되고 URL이 재작성된 HTML을 모듈의 JavaScript export와 함께 독립 실행형 .html 출력 파일로 생성할지 여부를 제어합니다. CSS 추출 파이프라인을 미러링합니다. experiments.html이 필요합니다.
true- 항상.html파일을 생성합니다.false- 생성하지 않습니다.'inline'- 독립 파일을 생성하지 않고 인라인 쓰기(예:<iframe srcdoc>)를 위해 처리된 HTML을 노출합니다.
설정하지 않으면, 컴파일 엔트리로 사용되는 HTML 모듈(HTML 엔트리 포인트)에 대해서는 기본적으로 true이고, JavaScript에서 import된 HTML 모듈에 대해서는 false입니다. 생성되는 파일명은 output.htmlFilename 및 output.htmlChunkFilename을 따릅니다.
webpack.config.js
export default {
experiments: { html: true },
module: {
generator: {
html: {
extract: true,
},
},
},
};module.parser
5.12.0+module.generator처럼 module.parser를 사용하여 한 곳에서 모든 파서의 옵션을 설정할 수 있습니다.
webpack.config.js
export default {
module: {
parser: {
asset: {
// asset 모듈 파서 옵션
// 애셋을 데이터 URI로 인라인하는 조건입니다.
// type: { maxSize: number } | ((source: string | Buffer, { filename, module }) => boolean)
dataUrlCondition: {
// 이 크기(바이트) 이하의 애셋을 인라인으로 처리합니다(기본값 8096).
maxSize: 8096,
},
},
"asset/inline": {
// 이 모듈 유형에는 아직 파서 옵션이 지원되지 않습니다.
},
"asset/resource": {
// 위와 동일
},
"asset/source": {
// 위와 동일
},
"asset/bytes": {
// 위와 동일
},
javascript: {
// javascript 모듈 파서 옵션
// 예. require.ensure 구문 파싱 활성화
requireEnsure: true,
// 모듈을 '엄격' 또는 '비엄격' 모드로 설정합니다. 엄격 모드와 비엄격 모드 간에 일부 동작이 다르기 때문에 이는 모듈의 동작에 영향을 미칠 수 있습니다.
overrideStrict: "non-strict",
// 트리 셰이킹을 위해 최상위 함수 이름을 사이드 이펙트 없음으로 표시, webpack 5.108.0부터 사용 가능
// type: string[]
pureFunctions: ["myPureFn"],
},
"javascript/auto": {
// 위와 동일
},
"javascript/dynamic": {
// 위와 동일
},
"javascript/esm": {
// 위와 동일
},
css: {
// CSS 모듈의 파서 옵션
// Webpack 5.97.0부터 사용 가능한 `@import` at-rules 처리를 활성화/비활성화합니다.
// type: boolean
import: true,
// webpack 5.97.0부터 사용 가능한 url()/image-set()/src()/image() 함수 처리를 활성화/비활성화합니다.
// type: boolean
url: true,
// Webpack 5.90.0부터 사용할 수 있는 CSS 내보내기를 위해 export라는 이름의 ES 모듈을 사용하세요.
// type: boolean
namedExports: true,
// CSS 콘텐츠가 내보내지는 방식을 설정합니다.
// type: string
exportType: "link",
// 파싱할 최상위 CSS 프로덕션 선택, webpack 5.108.0부터 사용 가능
// type: 'stylesheet' | 'block-contents'
as: "stylesheet",
},
"css/auto": {
// 위와 동일
},
"css/global": {
// 위와 동일
},
"css/module": {
// 위와 동일
},
html: {
// html 모듈에 대한 파서 옵션, `experiments.html` 필요, webpack 5.108.0부터 사용 가능
// URL-속성 추출을 비활성화하거나 커스터마이즈
// type: boolean | Array<'...' | { tag?: string, attribute: string, type: string, filter?: Function }>
sources: true,
// 파싱 전에 HTML 소스 변환
// type: (source: string, context: HtmlTemplateContext) => string
template: undefined,
},
// 그외 다른 옵션들…
},
},
};module.parser.css
CSS 파서에 대한 옵션을 설정합니다.
export default {
module: {
parser: {
css: {
// ...
namedExports: true,
},
},
},
};module.parser.css.import
이 옵션은 CSS 파일에서 @import at-rules를 처리할 수 있도록 합니다. true로 설정하면 @import 문이 처리되어 다른 CSS 파일에서 스타일을 모듈식으로 포함할 수 있습니다.
-
Type:
boolean -
Available: 5.97.0+
-
Example:
export default { 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.url
이 옵션은 CSS 파일 내 url(), image-set(), src(), image()와 같은 함수에서 URL 처리를 활성화 또는 비활성화합니다. 활성화하면 이러한 URL은 WebPack에서 확인 및 처리됩니다.
-
Type:
boolean -
Available: 5.97.0+
-
Example:
export default { module: { parser: { css: { url: true, }, }, }, };/* styles.css */ .background { background-image: url("./images/bg.jpg"); } .icon { content: image("./icons/star.svg"); }
module.parser.css.namedExports
이 옵션을 사용하면 CSS 내보내기에 export라는 이름의 ES 모듈을 사용할 수 있습니다. true로 설정하면 CSS 모듈은 이름이 지정된 내보내기를 사용하여 클래스와 스타일을 내보냅니다.
-
Type:
boolean -
Available: 5.90.0+
-
Example:
export default { module: { parser: { css: { namedExports: true, }, }, }, };
CSS 모듈에 대해 namedExports가 false인 경우 다양한 가져오기 방법을 사용하여 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); // styles.default를 통해 접근
console.log(styles.foo); // styles에서 직접 접근
console.log(styles1.foo); // 기본 가져오기를 통해 styles1에 접근
console.log(foo); // 바로 명명된 이름으로 가져오기namedExports가 활성화되면(기본 동작) 이름이 지정된 내보내기만 사용하여 CSS 클래스를 가져올 수 있습니다.
/* styles.css */
.header {
color: blue;
}
.footer {
color: green;
}import { footer, header } from "./styles.module.css";namedExports를 활성화하면 JavaScript 프로젝트에서 CSS를 관리하는 데 더 모듈화되고 유지 관리 가능한 접근 방식을 채택하고 ES 모듈 구문을 활용하여 더 명확하고 명시적인 가져오기를 수행할 수 있습니다.
module.parser.css.pure
5.107.0+CSS Modules에 대해 엄격한 pure mode를 활성화합니다. 모든 selector는 최소 하나의 local class 또는 id selector를 포함해야 하며, 그렇지 않으면 webpack이 build error를 발생시킵니다. 이는 postcss-modules-local-by-default의 pure mode와 동일한 동작이며, 실수로 작성한 global selector를 초기에 발견하는 데 도움이 됩니다.
- Type:
boolean - Default:
false - Available for:
css/module및css/auto(css/global에는 노출되지 않으며, 여기서는 global-by-default가 의도된 semantic입니다.)
webpack.config.js
export default {
experiments: { css: true },
module: {
parser: {
"css/module": {
pure: true,
},
},
},
};필요할 때는 두 가지 주석으로 이 검사를 비활성화할 수 있습니다.
/* cssmodules-pure-ignore */를 rule 바로 앞에 두면 해당 rule 하나에 대해서만 검사가 비활성화됩니다. 이 비활성화는 rule 단위로만 적용되며 하위 항목으로 전파되지 않습니다.
/* cssmodules-pure-ignore */
a {
/* 이 rule에 대해서만 검사 비활성화 */
color: blue;
}/* cssmodules-pure-no-check */를 파일 선두의 주석 영역(어떤 rule보다도 앞)에 두면 파일 전체에 대한 검사가 비활성화됩니다.
/* cssmodules-pure-no-check */
a {
/* 일반적으로 pure mode에서는 실패합니다 */
color: red;
}일부 구문은 설계상 검사 예외입니다. local selector를 포함한 상위 selector 내부의 nested rules는 pure-compliant로 간주되고, &는 부모 rule의 purity를 따르며, @keyframes와 @counter-style의 본문은 검사하지 않습니다.
module.parser.css.animation
5.104.0+CSS 모듈에서 @keyframes 애니메이션 이름 변경 기능을 활성화 또는 비활성화합니다. css/auto, css/module 및 css/global 모듈 타입에서만 사용 가능합니다.
- Type:
boolean - Default:
true
webpack.config.js
export default {
module: {
parser: {
"css/auto": {
animation: true, // Enable @keyframes renaming
},
},
},
};module.parser.css.container
5.104.0+CSS 모듈에서 @container 이름 변경을 활성화 또는 비활성화합니다. css/auto, css/module 및 css/global 모듈 타입에서만 사용 가능합니다.
- Type:
boolean - Default:
true
webpack.config.js
export default {
module: {
parser: {
"css/auto": {
container: true, // Enable @container renaming
},
},
},
};module.parser.css.customIdents
5.104.0+CSS 모듈에서 사용자 지정 식별자의 이름 변경을 활성화 또는 비활성화합니다. css/auto, css/module 및 css/global 모듈 타입에서만 사용 가능합니다.
- Type:
boolean - Default:
true
webpack.config.js
export default {
module: {
parser: {
"css/auto": {
customIdents: true, // Enable custom identifier renaming
},
},
},
};module.parser.css.customMedia
5.109.0+native CSS에서 @custom-media at-rule의 resolution을 활성화하거나 비활성화합니다. 이는 file-local build-time substitution입니다. media-type 값도 지원됩니다.
- Type:
boolean - Default:
true
@custom-media --narrow-window (max-width: 30em);
@media (--narrow-window) {
/* ... */
}webpack.config.js
export default {
module: {
parser: {
css: {
customMedia: false, // @custom-media resolution 비활성화
},
},
},
};module.parser.css.customSelectors
5.109.0+native CSS에서 @custom-selector at-rule의 resolution을 활성화하거나 비활성화합니다. 이는 :is(...)로 확장되는 file-local build-time expansion입니다.
- Type:
boolean - Default:
true
@custom-selector :--heading h1, h2, h3;
:--heading {
margin-top: 0;
}webpack.config.js
export default {
module: {
parser: {
css: {
customSelectors: false, // @custom-selector resolution 비활성화
},
},
},
};module.parser.css.dashedIdents
5.104.0+CSS 사용자 지정 속성(예: --my-variable)과 같은 하이픈으로 구분된 식별자의 이름 변경을 활성화 또는 비활성화합니다. css/auto, css/module 및 css/global 모듈 타입에서만 사용 가능합니다.
- Type:
boolean - Default:
true
webpack.config.js
export default {
module: {
parser: {
"css/auto": {
dashedIdents: true, // Enable dashed identifier renaming
},
},
},
};module.parser.css.function
5.104.0+CSS 모듈에서 @function 이름 변경을 활성화 또는 비활성화합니다. css/auto, css/module 및 css/global 모듈 타입에서만 사용 가능합니다.
- Type:
boolean - Default:
true
webpack.config.js
export default {
module: {
parser: {
"css/auto": {
function: true, // Enable @function renaming
},
},
},
};module.parser.css.fontPreload
5.109.0+HTML entry의 initial CSS에서 도달할 수 있는 각 @font-face의 primary src URL에 대해 <link rel="preload" as="font">를 자동 emit합니다. 모든 format을 preload하면 중복 다운로드가 발생하므로 @font-face마다 첫 번째 URL만 preload됩니다. module.parser.css.urlHints rule과 URL별 magic comment는 여전히 seed된 기본값을 override합니다.
- Type:
boolean - Default:
false
webpack.config.js
export default {
module: {
parser: {
css: {
fontPreload: true,
},
},
},
};module.parser.css.urlHints
5.109.0+CSS의 url(...)을 통해 참조되는 asset에 대한 기본 resource-hint rule입니다. module.parser.javascript.urlHints와 같은 rule 형식을 사용합니다.
- Type:
UrlHintRule[]
module.parser.css.grid
5.104.0+CSS 모듈에서 그리드 식별자 이름 변경 기능을 활성화 또는 비활성화합니다. css/auto, css/module 및 css/global 모듈 타입에서만 사용 가능합니다.
- Type:
boolean - Default:
true
webpack.config.js
export default {
module: {
parser: {
"css/auto": {
grid: true, // Enable grid identifier renaming
},
},
},
};module.parser.css.exportType
CSS 콘텐츠를 내보내는 방법을 설정합니다.
-
Type:
'link' | 'text' | 'css-style-sheet' | 'style' -
Available: 5.103.0+
-
Example:
export default { module: { parser: { css: { // ... exportType: "text", }, }, }, };
가능한 설정 값: 'link' | 'text' | 'css-style-sheet' | 'style'
link- CSS를 자체 파일로 추출하고link태그를 사용하여 DOM에 삽입합니다.text- CSS를 JS 파일에 저장하고 기본 내보내기를 사용하여 반환합니다.css-style-sheet- 기본 내보내기는 생성 가능한 스타일시트(예: CSSStyleSheet)입니다. 사용자 정의 요소와 Shadow DOM에 유용합니다.style- CSS를 JS 파일에 저장하고 런타임에<style>요소를 통해 DOM에 삽입합니다(5.106.0부터 사용 가능).
module.parser.css.as
파싱할 최상위 CSS 프로덕션을 선택합니다.
-
Type:
'stylesheet' | 'block-contents' -
Available: 5.108.0+
-
Example:
export default { experiments: { css: true }, module: { parser: { css: { as: "block-contents", }, }, }, };
가능한 값:
stylesheet(기본값) - 소스를 전체 스타일시트로 파싱합니다.block-contents- 소스를 CSS 블록의 내용(선언 목록)으로 파싱합니다. 즉, HTMLstyle="..."속성의 내부입니다.
module.parser.javascript
JavaScript 파서를 위한 옵션을 설정할 수 있습니다.
export default {
module: {
parser: {
javascript: {
// ...
commonjsMagicComments: true,
},
},
},
};Rule.parser에서 이러한 옵션을 설정하고 특정 모듈을 대상으로 지정할 수 있습니다.
module.parser.javascript.anonymousDefaultExportName
5.107.0+anonymous default-export function 및 class에 대해 webpack이 .name을 "default"로 설정할지 제어하며, 이는 native ESM의 ES spec과 일치합니다. 이 옵션을 활성화하면 webpack은 export에 Object.defineProperty(...)를 호출해 .name 값을 설정하는 작은 runtime helper(__webpack_require__.dn)를 주입합니다.
- Type:
boolean - Default: 애플리케이션에서는
true, 라이브러리에서는false(output.library가 설정된 경우)
애플리케이션은 기본적으로 spec-compliant 상태를 유지합니다. 반면 라이브러리는 .name === "default"에 의존하는 경우가 드물기 때문에, 번들 크기를 작게 유지하기 위해 이 helper를 생략합니다.
기본값을 명시적으로 덮어쓰려면 다음과 같이 설정합니다.
webpack.config.js
export default {
module: {
parser: {
javascript: {
anonymousDefaultExportName: false,
},
},
},
};module.parser.javascript.commonjsMagicComments
CommonJS를 위해 magic comments 지원을 활성화할 수 있습니다.
module.parser.javascript.createRequire
import { createRequire } from "module" 파싱 및 반환되는 require 함수 평가를 활성화하여, 이러한 호출이 실제 디펜던시가 되도록 합니다.
- Type:
boolean | string - Default:
target이 Node.js인 경우true, 그렇지 않으면false
문자열은 "module" 대신 createRequire를 가져올 모듈을 지정합니다.
module.parser.javascript.dynamicUrl
첫 번째 인수가 정적 문자열이 아닌 new URL() 파싱을 활성화합니다. 예: new URL(`./${name}.png`, import.meta.url). false로 설정하면 webpack이 정적으로 해석할 수 있는 URL만 애셋이 되고, 동적 URL은 작성된 그대로 유지됩니다.
- Type:
boolean - Default:
true
module.parser.javascript.strictThisContextOnImports
namespace 객체에 대해 사양이 요구하는 방식으로 import된 함수의 this 컨텍스트를 처리합니다. 즉, namespace 객체 대신 this === undefined로 호출합니다. 활성화하면 출력 크기가 약간 증가하므로 기본적으로 비활성화되어 있습니다.
- Type:
boolean - Default:
false
module.parser.javascript.worker
Web Worker 참조로 파싱되는 구문을 비활성화하거나 구성합니다.
- Type:
boolean | string[] - Default:
["Worker", "SharedWorker", "navigator.serviceWorker.register()", "Worker from worker_threads"]
항목은 생성자 이름("Abc"는 new Abc()를 처리), import된 바인딩("Abc from xyz"는 Abc가 xyz에서 import된 경우 new Abc()를 처리), 또는 함수 호출 표현식("abc.def()")입니다. "..."는 기본값을 나타내므로 대체가 아닌 확장이 됩니다. false로 설정하면 webpack이 worker를 전혀 번들링하지 않습니다.
webpack.config.js
export default {
module: {
parser: {
javascript: {
worker: ["MyWorker from ./my-worker.js", "..."],
},
},
},
};-
Type:
boolean -
Available: 5.17.0+
-
Example:
export default { module: { parser: { javascript: { commonjsMagicComments: true, }, }, }, };
webpackIgnore 주석만 지원됩니다.
const x = require(/* webpackIgnore: true */ "x");module.parser.javascript.dynamicImportCssPreload
동적으로 import된(import()) 모든 chunk의 CSS에 대해 <link rel="preload" as="style">을 자동으로 emit하여, stylesheet가 chunk의 JavaScript가 parse된 뒤가 아니라 JavaScript와 병렬로 fetch되게 합니다. dynamicImportPreload와 달리 JavaScript 자체는 preload되지 않습니다. true는 기본 순서를 사용하고, 숫자는 preload 순서를 설정합니다.
-
타입:
number | boolean -
가능한 버전: 5.109.0+
-
예제:
export default { module: { parser: { javascript: { dynamicImportCssPreload: true, }, }, }, };
module.parser.javascript.dynamicImportFetchPriority
동적 import를 위해 전역 fetchPriority를 지정합니다.
-
타입:
'low' | 'high' | 'auto' | false -
가능한 버전: 5.87.0+
-
예제:
export default { module: { parser: { javascript: { dynamicImportFetchPriority: "high", }, }, }, };
module.parser.javascript.dynamicImportMode
동적 import를 위한 전역 프리로드를 지정합니다.
-
타입:
'eager' | 'weak' | 'lazy' | 'lazy-once' -
가능한 버전: 5.73.0+
-
예제:
export default { module: { parser: { javascript: { dynamicImportMode: "lazy", }, }, }, };
module.parser.javascript.dynamicImportPrefetch
동적 import를 위한 전역 프리로드를 지정합니다.
-
타입:
number | boolean -
가능한 버전: 5.73.0+
-
예제:
export default { module: { parser: { javascript: { dynamicImportPrefetch: false, }, }, }, };
module.parser.javascript.dynamicImportPreload
동적 import를 위한 전역 프리로드를 지정합니다.
-
타입:
number | boolean -
가능한 버전: 5.73.0+
-
예제:
export default { module: { parser: { javascript: { dynamicImportPreload: false, }, }, }, };
module.parser.javascript.exportsPresence
\"import ... from ...\" 와 \"export ... from ...\"에서 내보내기 이름이 잘못된 경우의 동작을 지정합니다.
-
타입:
'error' | 'warn' | 'auto' | false -
가능한 버전: 5.62.0+
-
예제:
export default { module: { parser: { javascript: { exportsPresence: "error", }, }, }, };
module.parser.javascript.importExportsPresence
\"import ... from ...\"에서 내보내기 이름이 잘못된 경우의 동작을 지정합니다.
-
타입:
'error' | 'warn' | 'auto' | false -
가능한 버전: 5.62.0+
-
예제:
export default { module: { parser: { javascript: { importExportsPresence: "error", }, }, }, };
module.parser.javascript.importMeta
번들링 중에 webpack이 import.meta 표현식을 평가하는 방식을 제어합니다.
- 타입:
boolean | 'preserve-unknown' - 기본값:
true - 가능한 버전: 5.68.0+
- 타입:
boolean | 'preserve-unknown' | object - 기본값:
true - 가능한 버전: 5.68.0+
허용되는 값:
-
true- webpack은 알려진import.meta속성(예:import.meta.url,import.meta.webpackHot)을 평가합니다. 알려지지 않은 속성의 동작은 다른 구성(예:output.module)에 따라 달라집니다. -
false-import.meta평가를 모두 비활성화합니다. webpack은 표현식을 그대로 유지합니다. -
'preserve-unknown'5.105.0+ - 알려진 속성은 평소와 같이 평가하지만, 비표준 속성은 제거하는 대신 출력에 그대로 유지합니다. -
예시 -
import.meta평가를 완전히 비활성화합니다. -
object5.109.0+ - 개별import.metafield의 평가를 활성화하거나 비활성화합니다. 생략된 field는 계속 활성화되고, 알려지지 않은 field는 보존됩니다. 알려진 key는dirname,env,filename,main,resolve,url,webpack,webpackContext,webpackHot입니다. custom key도 허용되며 해당 custom field의 평가 여부를 제어합니다.export default { module: { parser: { javascript: { importMeta: { url: true, env: false, // `import.meta.env`를 그대로 둡니다. resolve: true, // `import.meta.resolve("./asset")`를 emit된 asset URL로 resolve합니다. webpackContext: true, }, }, }, }, }; -
예시 -
import.meta평가를 완전히 비활성화합니다.export default { module: { parser: { javascript: { importMeta: false, }, }, }, }; -
Example - preserve custom
import.metaproperties without enablingoutput.module:// webpack.config.js export default { module: { parser: { javascript: { importMeta: "preserve-unknown", }, }, }, };With this configuration, custom properties on
import.metaset by the build tool or runtime are preserved in the generated output:// import.meta.customProp은 외부에서 설정됩니다(예: build tool 또는 runtime). if (import.meta.customProp) { console.log(import.meta.customProp); }
module.parser.javascript.importMetaContext
import.meta.webpackContext 평가를 사용하거나 사용하지 않도록 설정합니다.
-
타입:
boolean -
가능한 버전: 5.70.0+
-
예제: W> webpack 5.109.0부터 deprecated되었습니다. 대신
importMeta.webpackContextobject 옵션을 사용하세요. 둘 다 설정된 경우importMeta.webpackContext가 우선합니다. -
타입:
boolean -
가능한 버전: 5.70.0+
-
예제:
export default { module: { parser: { javascript: { importMetaContext: true, }, }, }, };
module.parser.javascript.overrideStrict
모듈을 '엄격' 또는 '비엄격' 모드로 설정합니다. 엄격 모드와 비엄격 모드 간에 일부 동작이 다르기 때문에 이는 모듈의 동작에 영향을 미칠 수 있습니다.
-
Type:
'strict' | 'non-strict' -
Available: 5.93.0+
-
Example:
export default { module: { parser: { javascript: { overrideStrict: "non-strict", }, }, }, };
module.parser.javascript.pureFunctions
나열된 최상위 함수 이름을 사이드 이펙트 없음으로 표시하여, 결과가 사용되지 않는 해당 함수 호출이 트리 셰이킹될 수 있습니다. 이는 /*#__NO_SIDE_EFFECTS__*/ annotation의 명시적 설정 대응물입니다: 소스에 annotation을 달지 않고 이름을 나열합니다. 기본 export된 함수를 타겟팅하려면 "default"를 사용하세요.
-
Type:
string[] -
Available: 5.108.0+
-
Example:
export default { module: { rules: [ { test: /pure-source\.js$/, parser: { pureFunctions: ["createSelector", "styled", "default"], }, }, ], }, };
module.parser.javascript.reexportExportsPresence
\"export ... from ...\"에서 내보내기 이름이 잘못된 경우의 동작을 지정합니다. 이것은 TypeScript에서 타입을 다시 내보낼때 \"export ... from ...\"에서 \"export type ... from ...\"으로 마이그레이션하는 동안 비활성화하는 데 유용합니다.
-
타입:
'error' | 'warn' | 'auto' | false -
가능한 버전: 5.62.0+
-
예제:
export default { module: { parser: { javascript: { reexportExportsPresence: "error", }, }, }, };
module.parser.javascript.specNamespaceObject
이 모듈의 import * as ns 및 import()에 대해 webpack이 기본적으로 제공하는 일반 exports 객체 대신, 사양을 준수하는 Module Namespace Exotic Object를 제공합니다.
- Type:
boolean - Default:
false - Available: 5.111.0+
일반 exports 객체도 이미 [object Module]을 보고하고, 동일한 live binding을 가지며, export를 쓰거나 삭제하려 하면 TypeError를 발생시키므로 대부분의 코드는 두 객체를 구분하지 못합니다. spec 객체가 추가하는 것은 나머지 불변성입니다: Object.getPrototypeOf(ns)가 Object.prototype 대신 null이고, Object.isExtensible(ns)가 false입니다. 그래프 내에서 이를 확인하는 것이 있을 때 — 적합성 테스트나 실제 namespace를 feature-detect하는 라이브러리 — 일반 설정으로 사용하지 말고 해당 경우에만 사용하세요.
Proxy로 구현되어 추가 런타임 코드가 필요하므로, 전역적으로 활성화하지 말고 일반적으로 Rule.parser를 통해 모듈별로 활성화하세요:
export default {
module: {
rules: [
{
test: /\.js$/,
include: /node_modules\/strict-package/,
parser: {
specNamespaceObject: true,
},
},
],
},
};module.parser.javascript.strictModeViolations
module이 ES module output(output.module)으로 emit될 때 strict mode에서 runtime에 깨지는 구문의 동작을 지정합니다. strict-mode-only syntax(변수의 delete, with, 8진 literal 및 escape, 중복 parameter, eval/arguments에 할당)와 semantic hazard(arguments.callee/arguments.caller, 읽기 전용 global에 할당)를 포함합니다.
-
타입:
'error' | 'warn' | false -
기본값:
'warn'(experiments.futureDefaults가 활성화되면'error') -
가능한 버전: 5.109.0+
-
예제:
export default { module: { parser: { javascript: { strictModeViolations: "error", }, }, }, };
module.parser.javascript.url
new URL() 구문 파싱을 활성화합니다.
-
타입:
boolean = true|'relative' -
예제:
export default { module: { parser: { javascript: { url: false, // `new URL()` 구문 파싱 비활성화 }, }, }, };
module.parser.javascript.url의 'relative' 값은 webpack 5.23.0부터 사용할 수 있습니다. 사용하면 webpack은 new URL() 구문에 대한 상대경로 URL을 생성합니다. 즉, 결과 URL 기준 URL이 포함되지 않습니다.
<!-- 'relative'인 경우 -->
<img src="c43188443804f1b1f534.svg" />
<!-- 'relative'가 아닌 경우 -->
<img src="file:///path/to/project/dist/c43188443804f1b1f534.svg" />- 이것은 기준 URL이 서버에의 알려지지 않을 때 SSR(서버 사이드 렌더링)에 유용하며 몇 바이트를 절약할 수 있습니다. 동일하게 유지하기 위해서 클라이언트 빌드에서도 사용해야 합니다.
- 또한 서버 측 렌더링이 일반적으로 필요한 정적 사이트 생성기, mini-css-plugin 및 html-plugin 등을 위해서도 필요합니다.
module.parser.javascript.urlHints
이 parser가 찾은 URL 참조 asset(new URL("./asset", import.meta.url))에 대한 기본 resource-hint rule입니다. 일치하는 rule은 webpackPrefetch / webpackPreload / webpackAs / webpackType / webpackMedia / webpackFetchPriority magic comment와 같은 field를 설정합니다. 같은 URL에 명시적인 magic comment가 있으면 여전히 그것이 우선합니다. emit된 hint는 output.resourceHints pipeline의 일부입니다.
각 rule은 다음을 지원합니다.
test/include/exclude: asset의 request와 매칭되는 Rule conditions입니다. 세 항목을 모두 생략하면 모든 asset에 rule을 적용합니다.prefetch(boolean): 일치하는 asset에 대해<link rel="prefetch">를 emit합니다.preload(boolean): 일치하는 asset에 대해<link rel="preload">를 emit합니다.as(string): 기본asattribute입니다(script/style/font/image/ ...).type(string): 기본typeattribute입니다(예:"font/woff2").media(string): 기본mediaattribute입니다(예:"(min-width: 800px)").fetchPriority('low' | 'high' | 'auto' | false): emit된 link의 기본fetchpriority입니다.
같은 옵션은 CSS parser(url(...) 참조)와 HTML parser(<img src> / <link href> / <script src> 참조)에도 있으며, output.resourceHints.urlHints는 세 parser 모두에 적용되는 project-wide shorthand입니다.
-
타입:
UrlHintRule[] -
가능한 버전: 5.109.0+
-
예제:
export default { module: { parser: { javascript: { urlHints: [{ test: /\.woff2$/, preload: true, as: "font" }], }, }, }, };
module.parser.javascript.worklet
context.audioWorklet.addModule() 또는 CSS.paintWorklet.addModule() 같은 Worklet syntax의 parsing을 비활성화하거나 구성합니다. 활성화하면 addModule(new URL("./worklet.js", import.meta.url)) entry가 Worker처럼 번들됩니다. ES module output에서는 worklet의 split chunk가 native import를 통해 연결되고, script output에서는 script worklet이 runtime에 chunk를 로드할 수 없으므로 addModule을 통해 미리 추가됩니다.
- 타입:
boolean | string[] - 기본값: 비활성화.
experiments.futureDefaults가 켜져 있으면 기본 syntax 목록으로 활성화됩니다. - 가능한 버전: 5.109.0+
기본 syntax 목록은 다음과 같습니다.
[
"*context.audioWorklet.addModule()",
"*audioWorklet.addModule()",
"CSS.paintWorklet.addModule()",
"CSS.layoutWorklet.addModule()",
"CSS.animationWorklet.addModule()",
];배열을 사용하면 어떤 syntax를 Worklet 참조로 parse할지 custom할 수 있습니다. 예를 들어 '*context.audioWorklet.addModule()'은 context.audioWorklet.addModule()을 처리하고, 'abc()'는 abc()를 처리합니다. 조합도 가능합니다.
-
예제:
export default { module: { parser: { javascript: { worklet: [ "*audioWorklet.addModule()", "CSS.paintWorklet.addModule()", ], }, }, }, };
module.parser.javascript.parse
5.103.0+Webpack의 내장 파서 대신 사용자 지정 JavaScript 파싱 함수를 사용하세요.
Webpack의 AST 분석이 올바르게 작동하도록 ast, comments, semicolons를 반환하세요.
ast는 ESTree와 호환되어야 합니다.comments는 ESTree 주석 노드의 배열입니다.semicolons는 파서가 세미콜론을 삽입한 위치의 집합입니다.
-
Type:
(code: string, options: ParseOptions) => ParseResult -
예시:
export default { module: { parser: { javascript: { parse: (code, options) => { const comments = []; const semicolons = new Set(); const onInsertedSemicolon = (pos) => semicolons.add(pos); const parseOptions = { ...options, module: options.sourceType === "module", loc: options.locations, onComment: options.comments ? comments : undefined, onInsertedSemicolon: options.semicolons ? onInsertedSemicolon : undefined, }; const ast = meriyah.parse(code, parseOptions); return { ast, comments, semicolons }; }, }, }, }, };
module.parser.javascript.typescript
TypeScript 구문을 파싱합니다. experiments.typescript를 기본값으로 사용하므로, 해당 실험을 활성화하면 자동으로 켜집니다; 규칙별로 재정의하려면 여기서 설정하세요.
- Type:
boolean
module.parser.javascript.deferImport
TC39 deferred module evaluation 제안(import defer * as ns from "...")을 파싱합니다. experiments.deferImport를 기본값으로 사용합니다.
- Type:
boolean
module.parser.javascript.sourceImport
TC39 source phase imports 제안(import source x from "...")을 파싱합니다. experiments.sourceImport를 기본값으로 사용합니다.
- Type:
boolean
Syntax toggles
각각은 하나의 모듈 구문 파싱을 켜거나 끕니다. boolean 값을 받으며, 모두 동일한 기본값을 가지지 않습니다 — 세 가지는 명시적으로 설정하기 전까지 비활성화되거나 경고를 표시합니다:
| Option | Syntax | Default |
|---|---|---|
amd | AMD — define(), require([...], cb) | 활성화 |
browserify | browserify 전용 처리 | 활성화 |
commonjs | CommonJS — require(), module.exports | 활성화 |
harmony | ECMAScript modules — import / export | 활성화 |
import | import() | 활성화 |
requireContext | require.context() | 활성화 |
requireEnsure | require.ensure() | 활성화 |
requireInclude | require.include() | 활성화, 단 명시적으로 설정하지 않으면 deprecated 경고 표시 |
requireJs | RequireJS 전용 — require.config, require.version | true로 설정하지 않으면 비활성화 |
system | System.js — System.import, System.register | true로 설정하지 않으면 비활성화 |
node | Node.js 내장 — __dirname, __filename, global | node와 동일한 형식; false로 설정하면 처리 비활성화 |
webpack.config.js
export default {
module: {
parser: {
javascript: {
// this project has no AMD, so do not pay to parse for it
amd: false,
// opt in to the two that are off by default
system: true,
},
},
},
};module.parser.json
JSON 파서에 대한 옵션을 설정합니다.
export default {
module: {
parser: {
json: {
// 옵션
},
},
},
};module.parser.json.exportsDepth
exportInfo로 표시된 JSON 종속성의 깊이입니다.
module.parser.json.exportsDepth의 기본값은 mode에 따라 달라집니다.
| 모드 | 기본값 |
|---|---|
"production" | Infinity |
"development" | 1 |
"none" | Infinity |
- Type:
number - Available: 5.98.0+
- Example:
export default {
module: {
parser: {
json: {
// 예를 들면, 다음 json의 경우에는
// {
// "depth_1": {
// "depth_2": {
// "depth_3": "foo"
// }
// },
// "_depth_1": "bar"
// }
// `exportsDepth: 1`, `depth_2` 및 `depth_3`은 `exportInfo`로 플래그가 지정되지 않습니다.
exportsDepth: 1,
},
},
},
};module.parser.json.namedExports
객체 유형의 JSON에 대해 명명된 내보내기를 허용합니다.
- Type:
boolean - Available: 5.103.0+
- Example:
export default {
module: {
parser: {
json: {
// 예시:
// import { myField } from "./file.json";
//
// console.log(myField);
namedExports: true,
},
},
},
};module.parser.json.parse
콘텐츠를 파싱하고 JSON을 반환하는 함수입니다.
- Type:
((input: string) => Buffer | JsonValue) - Example:
import json5 from "json5";
export default {
module: {
parser: {
json: {
parse: json5.parse,
},
},
},
};module.parser.html
5.108.0+HTML 파서에 대한 옵션을 설정합니다. 이러한 옵션은 experiments.html 플래그를 활성화해야 합니다.
export default {
experiments: { html: true },
module: {
parser: {
html: {
// ...
sources: true,
},
},
},
};module.parser.html.sources
URL과 유사한 속성 값(<img src>, <link href>, <script src> 등)을 webpack 의존성으로 추출하는 것을 제어합니다.
- Type:
boolean | Array<'...' | { tag?: string, attribute: string, type: string, filter?: (attributes: Map<string, string>) => boolean }> - Available: 5.108.0+
가능한 값:
true(기본값) - 내장된 소스 목록을 사용하여 URL과 유사한 속성을 추출합니다.false- 추출을 완전히 비활성화합니다. URL과 유사한 속성은 그대로 유지되며<script src>,<link rel="modulepreload">및<link rel="stylesheet">는 더 이상 컴파일 엔트리가 되지 않습니다. 인라인<script>및<style>본문은 여전히 처리됩니다. 개별 URL을 건너뛰려면webpackIgnore주석 또는IgnorePlugin을 사용하세요.- 배열 - URL로 처리할
tag/attribute쌍을 커스터마이즈합니다. 내장 기본값을 유지하려면 리터럴 문자열"..."를 포함하세요."..."가 없는 배열은 기본값을 완전히 제외합니다.
각 배열 항목 객체는 다음을 허용합니다:
attribute(필수) - 값이 URL인 속성 이름입니다.type(필수) - 값이 파싱되고 번들되는 방식. 다음 중 하나:src- 일반 애셋으로 번들되는 단일 URL.srcset- 일반 애셋의srcset스타일 후보 목록.script-<script src>와 같은 클래식 청크 엔트리.script-module-<script type="module" src>와 같은 ES 모듈 청크 엔트리.stylesheet-<link rel="stylesheet">와 같은 CSS 청크 엔트리.stylesheet-style- 속성 값이 전체 인라인 스타일시트(<style>본문과 같음)로 처리되고 CSS 파이프라인을 통해 라우팅됩니다.stylesheet-style-attribute- 속성 값이 CSS 블록의 내용(style속성과 같음)으로 처리되고 CSS 파이프라인을 통해 라우팅됩니다.css-url- CSS 값 속성(예: SVGstyle표현 속성)에서url()참조를 추출합니다. webpack 5.108.0부터 사용 가능합니다.
tag(선택) - 매치할 태그 이름. 모든 요소를 매치하려면 생략하세요.filter(선택) -(attributes: Map<string, string>) => boolean; 주어진 요소에 대해 이 항목을 건너뛰려면false를 반환합니다.srcdoc- attribute 값을 entity-encoded HTML document(<iframe srcdoc>와 같음)로 처리하고 HTML pipeline을 통해 번들합니다. webpack 5.108.0부터 사용할 수 있습니다.html5.109.0+ - URL은 자체 emit page로 번들되는 다른 HTML 파일에 대한 link이며(asset 추출 포함), attribute는 page의 output filename으로 다시 작성됩니다(Parcel의<a href="page.html">와 유사).false5.109.0+ - 이tag/attribute의 내장 source를 비활성화합니다."..."와 함께 사용해 기본값 하나를 제거할 수 있습니다. 예를 들어<img src>를 URL로 처리하지 않게 할 수 있습니다.
tag(선택) - 매치할 tag 이름입니다. 모든 element를 매치하려면 생략하세요.filter(선택) -(attributes: Map<string, string>, value: string) => boolean; 주어진 element에 대해 이 항목을 건너뛰려면false를 반환합니다.
export default {
experiments: { html: true },
module: {
parser: {
html: {
sources: [
"...", // 내장 기본값 유지
{ tag: "img", attribute: "data-src", type: "src" },
{ tag: "img", attribute: "data-srcset", type: "srcset" },
{ attribute: "data-href", type: "src" }, // 모든 태그
{ tag: "img", attribute: "src", type: false }, // 내장 기본값 제거
],
},
},
},
};webpack 5.109.0부터 내장 source 목록은 asset을 포함하는 HTML을 더 많이 인식합니다. script와 style이 chunk로 번들되고 빌드된 chunk URL로 다시 작성되는 <link rel="preload"> / <link rel="prefetch"> link, twitter:player:stream meta content, legacy SVG font-face-uri, cursor, altGlyph, tref, glyphRef element 참조, 그리고 <link rel="manifest"> Web App Manifest 내부의 icons / screenshots / shortcuts URL이 여기에 포함됩니다.
module.parser.html.as
5.109.0+HTML source가 parse되는 방식을 구성합니다.
- Type:
'document' | string - Default:
'document'
'document'는 전체 page를 parse합니다. 다른 값은 context element의 tag 이름입니다. source는 해당 element의 inner HTML(fragment)로 parse됩니다. 예를 들어 중립적인 fragment에는 'template'을 사용하고, bare <tr> / <td> 같은 context-sensitive tag가 제거되지 않고 유지되도록 하려면 'tbody'를 사용합니다.
export default {
module: {
parser: {
html: {
as: "template",
},
},
},
};module.parser.html.urlHints
5.109.0+HTML attribute(<img src>, <link href>, <script src>)에서 참조되는 asset에 대한 기본 resource-hint rule입니다. module.parser.javascript.urlHints와 같은 rule 형식을 사용합니다.
- Type:
UrlHintRule[]
module.parser.html.template
파서가 의존성을 추출하기 전에 원시 HTML 소스를 변환하여, 템플릿 언어(Handlebars, EJS, Eta 등)에서 생성된 URL이 여전히 발견되고 번들됩니다. 함수는 동기적으로 실행되며 파싱할 HTML 문자열을 반환해야 합니다.
- Type:
(source: string, context: HtmlTemplateContext) => string - Available: 5.108.0+
context 객체는 현재 module, 해당 resource 경로, 빌드 의존성 등록 헬퍼(addDependency, addContextDependency, addMissingDependency, addBuildDependency), 그리고 emitWarning / emitError를 제공합니다.
export default {
experiments: { html: true },
module: {
parser: {
html: {
template: (source, { resource, addDependency }) => {
addDependency(resource);
return source
.replaceAll("{{title}}", "Hello world")
.replaceAll("{{image}}", "./image.png");
},
},
},
},
};module.noParse
RegExp string (request: string) => boolean (RegExp | string | ((request: string) => boolean))[]
webpack이 주어진 정규식과 일치하는 파일을 파싱하지 못하도록 합니다. 제외된 파일에는 import, require, define 또는 기타 import 메커니즘의 호출이 없어야 합니다. 이렇게 하면 큰 라이브러리를 무시할 때 빌드 성능을 향상 시킬 수 있습니다.
'noParse'는 모든 'import', 'require', 'define' 등의 호출이 런타임에서 도달할 수 없는 경우 확장을 의도적으로 방지하는 방법으로도 사용할 수 있습니다.
예를 들어 '브라우저' 대상용 프로젝트를 빌드하고 브라우저와 Node.js 모두에 대해 사전 빌드된 타사 라이브러리를 사용할 때, 예를 들면 require('os')와 같은 Node.js의 내장 기능이 필요합니다.
webpack.config.js
export default {
// ...
module: {
noParse: /jquery|lodash|src[\\/]vendor[\\/]somelib/,
},
};export default {
// ...
module: {
noParse: (content) =>
/jquery|lodash|src[\\/]vendor[\\/]somelib/.test(content),
},
};module.unsafeCache
boolean (module: Module) => boolean
모듈 요청에 대한 해석을 캐시합니다. module.unsafeCache에 대한 몇 가지 기본값이 있습니다.
webpack.config.js
export default {
// ...
module: {
unsafeCache: false,
},
};module.rules
(Rule | undefined | null | false | "" | 0 | "...")[]
모듈이 생성 될 때 요청과 일치하는 Rule의 배열입니다. 이러한 규칙은 모듈 생성 방법을 수정할 수 있습니다. 로더를 모듈에 적용시키거나 파서를 수정할 수 있습니다.
Webpack 5.87.0부터 false, undefined, null 및 0과 같은 falsy 값을 사용하여 조건부로 규칙을 비활성화할 수 있습니다.
Rule
object
Rule은 Conditions, Results 그리고 중첩된 Rules 세 부분으로 나눠질 수 있습니다.
Rule Conditions
conditions에 대한 두가지 입력 값이 있습니다.
-
resource: 요청된 파일의 절대 경로입니다.
resolve규칙에 따라 이미 해석되었습니다. -
issuer: resource를 요청한 모듈의 파일에 대한 절대 경로입니다. import하는 위치입니다.
예: app.js 내에서 import './style.css'를 수행할 때, resource는 /path/to/style.css이고 issuer는 /path/to/app.js입니다.
Rule의 test, include, exclude 그리고 resource 프로퍼티가 resource와 일치하고 issuer 프로퍼티가 issuer와 일치합니다.
webpack 5.110.0부터 운영체제와 무관한 glob과 리소스 자체 패키지 내부 경로인 descriptionRelativePath로도 리소스를 일치시킬 수 있습니다.
여러 조건을 사용하면 모든 조건이 일치해야 합니다.
Rule results
Rule results는 Rule condition이 일치하는 경우에만 사용됩니다.
Rule에는 두 가지 출력 값이 있습니다.
- 적용된 로더: resource에 적용된 로더의 배열입니다.
- 파서 옵션: 모듈에 대한 파서를 만드는 데 사용해야하는 옵션 객체입니다.
loader, options, use 프로퍼티는 로더에 영향을 줍니다.
enforce 프로퍼티는 loader 카테고리에 영향을 줍니다. normal, pre, post loader 중 어느 것인지를 결정합니다.
parser 프로퍼티는 파서 옵션에 영향을 줍니다.
Nested rules
중첩된 rules은 rules, oneOf 프로퍼티에서 지정할 수 있습니다.
이러한 rule은 상위 Rule condition이 일치하는 경우에만 평가됩니다. 각 중첩 rule은 자체적으로 조건을 포함 할 수 있습니다.
평가의 순서는 다음과 같습니다.
Rule.assert
종속성의 가져오기 어설션을 일치시키고 어설션 유형에 따라 특정 규칙을 적용할 수 있는 조건입니다.
webpack.config.js
export default {
// ...
module: {
rules: [
{
// "assert { type: 'json' }" 어설션을 사용하여 가져오기를 처리합니다.
assert: { type: "json" },
loader: import.meta.resolve("./loader-assert.js"),
},
],
},
};index.js
import one from "./pkg-1.json" assert { type: "json" };이 예에서는 Rule.assert를 사용하여 assert { type: "json" }이라는 어설션과 함께 가져온 모든 모듈에 loader-assert.js를 적용하여 JSON 파일이 올바르게 처리되는지 확인합니다.
Rule.compiler
하위 컴파일러 이름을 일치시킬 수 있는 조건.
webpack.config.js
export default {
// ...
name: "compiler",
module: {
rules: [
{
test: /a\.js$/,
compiler: "compiler", // "컴파일러" 이름과 일치하면 로더가 적용됩니다.
use: "./loader",
},
{
test: /b\.js$/,
compiler: "other-compiler", // "컴파일러" 이름과 일치하지 않으므로 로더가 적용되지 않습니다.
use: "./loader",
},
],
},
};Rule.descriptionRelativePath
5.110.0+모듈의 description 파일(일반적으로 가장 가까운 package.json) 디렉터리를 기준으로 한 경로(예: ./lib/button.js)와 일치하는 Condition입니다. 경로는 항상 slash를 사용하므로 모든 운영체제에서 같은 규칙이 일치합니다.
hoist된 node_modules, pnpm store, workspace symlink처럼 설치 구조에 따라 달라지는 절대 위치 대신 패키지 내부 위치로 파일을 지정할 때 사용합니다.
webpack.config.js
export default {
// ...
module: {
rules: [
{
descriptionData: {
name: "some-package",
},
descriptionRelativePath: /^\.\/src\//,
// ...
},
],
},
};match resource가 리소스를 교체한 경우 원래 요청의 description 파일이 더 이상 해당 리소스를 설명하지 않으므로 이 조건을 적용하지 않습니다.
Rule.enforce
string
가능한 값: 'pre' | 'post'
로더의 범주를 지정합니다. 값이 없으면 일반 로더를 의미합니다.
추가적으로 import/require의 인라인으로 적용된 "인라인 로더"도 있습니다.
모든 로더가 차례로 통과하는 두 단계가 있습니다.
- Pitching 단계: 로더의 pitch 메소드는
post, inline, normal, pre순서로 호출됩니다. 자세한 내용은 Pitching Loader를 참고하세요. - Normal 단계: 로더의 normal 메소드는
pre, normal, inline, post순서로 호출됩니다. 모듈의 소스 코드에서 변환이 이 단계에서 발생합니다.
모든 일반 로더는 요청에 !를 접두사로 추가하여 생략(재정의) 할 수 있습니다.
모든 일반 및 사전 로더는 요청에 -!를 접두사로 추가하여 생략(재정의) 할 수 있습니다.
모든 일반, 사후 및 사전 로더는 요청에 !!를 접두사로 추가하여 생략(재정의) 할 수 있습니다.
// 일반 로더 비활성화
import { a } from "!./file1.js";// 사전, 일반 로더 비활성화
import { b } from "-!./file2.js";// 모든 로더 비활성화
import { c } from "!!./file3.js";인라인 로더와 ! 접두사는 비표준이므로 사용해서는 안됩니다. 이것들은 로더가 생성한 코드에서 사용할 수 있습니다.
Rule.exclude
조건과 일치하는 모든 모듈을 제외합니다. Rule.exclude 옵션을 사용하면 Rule.resource 옵션을 사용할 수 없습니다. 자세한 내용은 Rule.resource 및 Condition.exclude를 참고하세요.
Rule.include
조건과 일치하는 모든 모듈을 포함합니다. Rule.include 옵션을 사용하면 Rule.resource 옵션을 사용할 수 없습니다. 자세한 내용은 Rule.resource 및 Condition.include를 참고하세요.
Rule.glob
5.110.0+string string[]
모듈 리소스를 하나 이상의 glob pattern과 일치시킵니다. 정규 표현식과 달리 glob은 모든 운영체제에서 같은 방식으로 일치합니다. pattern과 검사 경로 모두에서 /와 \를 경로 구분자로 읽으므로 macOS에서 작성한 규칙이 Windows에서도 일치합니다. 그렇지 않은 정규 표현식 조건을 보고하는 performance.osDependentRules도 참고하세요.
webpack.config.js
export default {
// ...
module: {
rules: [
{
glob: "src/**/*.css",
type: "css/module",
},
],
},
};여러 pattern은 OR로 결합되고 ! 접두사는 일치 항목을 제외합니다. ! pattern만 포함한 목록은 전체 항목에서 대상을 제외하므로 제외 목록으로 동작합니다.
export default {
// ...
module: {
rules: [
{
// test 및 생성 파일을 제외한 모든 .ts 파일
glob: ["**/*.ts", "!**/*.test.ts", "!**/generated/**"],
loader: "ts-loader",
},
],
},
};상대 pattern은 모든 깊이에서 일치하므로 "src/**/*.css"는 packages/ui/src/theme.css와도 일치합니다. 특정 디렉터리로 제한하려면 절대 경로로 pattern을 시작하세요.
glob은 다른 조건과 결합됩니다. test, include, exclude도 함께 일치해야 합니다. Condition 객체 안에서도 사용할 수 있어 condition을 받는 모든 위치에서 사용할 수 있습니다.
export default {
// ...
module: {
rules: [
{
test: /\.js$/,
include: { glob: "src/**" },
loader: "babel-loader",
},
],
},
};Rule.issuer
요청한 모듈과 비교할 Condition입니다. 아래의 예제에서, a.js의 issuer는 index.js 파일의 경로입니다.
index.js
import A from "./a.js";이 옵션은 특정 모듈 또는 모듈 세트의 디펜던시에 로더를 적용하는 데 사용할 수 있습니다.
Rule.issuerLayer
issuer의 계층별로 필터링하고 일치시킬 수 있습니다.
webpack.config.js
export default {
// ...
module: {
rules: [
{
issuerLayer: "other-layer",
},
],
},
};Rule.layer
string
모듈이 배치될 레이어를 지정합니다. 모듈 그룹을 하나의 레이어로 묶어 split chunks, stats 또는 entry options에서 사용할 수 있습니다.
동적 import(`./dir/${name}`)를 통해 도달하는 모듈은 context 모듈을 통해 해석되며, 이는 import한 모듈의 레이어를 상속합니다. 따라서 해석될 수 있는 모듈들은 규칙이 다른 위치에 배치하지 않는 한 import한 모듈의 레이어에 배치됩니다. 이는 정적으로 import된 모듈과 동일한 방식입니다.
모듈이 최종적으로 배치된 레이어는 모듈 자체에서 __webpack_layer__로 읽을 수 있습니다.
webpack.config.js
export default {
// ...
module: {
rules: [
{
test: /module-layer-change/,
layer: "layer",
},
],
},
};Rule.extractSourceMap
boolean = false
파일에서 기존 소스 맵 데이터를 추출합니다(//# sourceMappingURL 주석에서). 이는 타사 라이브러리의 소스 맵을 보존하는 데 유용합니다.
webpack.config.js
export default {
// ...
module: {
rules: [
{
test: /\.m?js$/,
extractSourceMap: true,
},
],
},
};Rule.loader
Rule.loader는 Rule.use: [ { loader } ]의 단축어입니다. 자세한 내용은 Rule.use와 UseEntry.loader를 참고하세요.
Rule.loaders
대신 Rule.use를 사용하세요.
Rule.mimetype
mimetype을 사용하여 설정 규칙을 데이터 URI에 일치시킬 수 있습니다.
webpack.config.js
export default {
// ...
module: {
rules: [
{
mimetype: "application/json",
type: "json",
},
],
},
};application/json, text/javascript, application/javascript, application/node 및 application/wasm은 이미 기본적인 mimetype으로 포함되어 있습니다.
Rule.oneOf
Rule이 일치할 때 첫 번째 일치하는 Rule만 사용되는 Rules의 배열입니다.
webpack.config.js
export default {
// ...
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.options는 Rule.use: [ { options } ]의 단축어입니다. 자세한 내용은 Rule.use와 UseEntry.options를 참고하세요.
Rule.parser
파서 옵션이 있는 객체입니다. 적용된 모든 파서 옵션이 병합됩니다.
파서는 이러한 옵션을 검사하고 그에 따라 자체적으로 비활성화하거나 재구성할 수 있습니다. 대부분의 기본 플러그인은 값을 다음과 같이 해석합니다.
- 옵션을
false로 설정하면 파서가 비활성화됩니다. - 옵션을
true로 설정하거나undefined로 두면 파서가 활성화됩니다.
그러나, 파서 플러그인은 boolean 이상의 값을 받아들일 수 있습니다. 예를 들면, 내부의 NodeStuffPlugin은 true 대신에 객체를 받아 특정 Rule에 대한 옵션을 추가할 수 있습니다.
예제 (기본 플러그인의 파서 옵션):
import path from "node:path";
import { fileURLToPath } from "node:url";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
export default {
// ...
module: {
rules: [
{
// ...
parser: {
amd: false, // AMD 비활성화
commonjs: false, // CommonJS 비활성화
system: false, // SystemJS 비활성화
harmony: false, // ES2015 Harmony import/export 비활성화
requireInclude: false, // require.include 비활성화
requireEnsure: false, // require.ensure 비활성화
requireContext: false, // require.context 비활성화
browserify: false, // Browserify 번들의 특수 처리 비활성화
requireJs: false, // requirejs.* 비활성화
commonjsMagicComments: false, // CommonJS를 위한 magic comments 지원 비활성화
node: {}, // 모듈 수준에서 [node](/configuration/node) 계층 재구성
// 또는
// node: false, // __dirname, __filename 등을 비활성화합니다.
worker: ["default from web-worker", "..."], // javascript 파일에 대한 WebWorker 처리를 커스터마이즈합니다. "..."는 기본값을 나타냅니다.
},
},
],
},
};Rule.type이 asset이면 Rules.parser 옵션은 파일 내용을 Base64로 인코딩할지 또는 별도의 파일로 출력 디렉터리에 내보낼 지 여부를 나타내는 조건을 설명하는 객체 또는 함수일 수 있습니다.
Rule.type이 asset 또는 asset/inline인 경우 Rule.generator옵션은 모듈 소스의 인코딩을 설명하는 객체이거나 사용자 지정 알고리즘으로 모듈의 소스를 인코딩하는 함수일 수 있습니다.
추가적인 정보나 사용 사례를 위해 애셋 모듈 가이드를 참고하세요.
Rule.parser.dataUrlCondition
{ maxSize?: number = 8096 } (source: string | Buffer, context: { filename: string, module: Module }) => boolean
모듈 소스 크기가 maxSize 이하이면 모듈은 Base64로 인코딩된 문자열로 번들에 삽입되고, 그렇지 않으면 모듈 파일이 출력 디렉터리에 생성됩니다.
webpack.config.js
export default {
// ...
module: {
rules: [
{
// ...
parser: {
dataUrlCondition: {
maxSize: 4 * 1024,
},
},
},
],
},
};함수를 dataUrlCondition의 값으로 설정한 경우에는 true를 반환하면 webpack이 모듈을 Base64 인코딩 문자열로 번들에 삽입하도록 지시합니다. 그렇지 않으면 모듈 파일이 출력 디렉터리로 내보내집니다.
webpack.config.js
export default {
// ...
module: {
rules: [
{
// ...
parser: {
dataUrlCondition: (source, { filename, module }) => {
const content = source.toString();
return content.includes("some marker");
},
},
},
],
},
};Rule.generator
Rule.generator.dataUrl
{ encoding?: 'base64' | false = 'base64', mimetype?: string } (content: string | Buffer, context: { filename: string, module: Module }) => string
Rule.generator.dataUrl이 객체로 사용되면 두개의 프로퍼티를 설정할 수 있습니다.
- encoding:
'base64'로 설정하면 모듈 소스는 Base64 알고리즘을 사용하여 인코딩됩니다.encoding을 false로 설정하면 인코딩이 비활성화됩니다. - mimetype: 데이터 URI의 MIME 유형입니다. 기본적으로 모듈 리소스 확장에서 확인합니다.
webpack.config.js
export default {
// ...
module: {
rules: [
{
// ...
generator: {
dataUrl: {
encoding: "base64",
mimetype: "mimetype/png",
},
},
},
],
},
};함수로 사용하면 모든 모듈에 대해 실행되며 데이터 URI 문자열을 반환해야 합니다.
export default {
// ...
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
애셋 모듈에서 애셋 쓰기를 하지 않는 경우, 서버 사이드 랜더링에서 사용할 수 있습니다.
-
타입:
boolean = true -
가능한 버전: 5.25.0+
-
예제:
export default { // … module: { rules: [ { test: /\.png$/i, type: "asset/resource", generator: { emit: false, }, }, ], }, };
Rule.generator.filename
output.assetModuleFilename과 동일하지만 특정 규칙에 사용됩니다. output.assetModuleFilename을 재정의하고 asset 및 asset/resource 모듈 유형에서만 작동합니다.
webpack.config.js
export default {
// ...
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
특정 애셋 모듈에 대해 publicPath를 사용자 지정합니다.
- 타입:
string | ((pathData: PathData, assetInfo?: AssetInfo) => string) - 가능한 버전: 5.28.0+
export default {
// ...
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+
export default {
// ...
output: {
publicPath: "static/",
},
module: {
rules: [
{
test: /\.png$/i,
type: "asset/resource",
generator: {
publicPath: "https://cdn/assets/",
outputPath: "cdn-assets/",
},
},
],
},
};Rule.resource
리소스와 일치하는 Condition입니다. 자세한 내용은 규칙 조건을 참고하세요.
Rule.realResource
실제 리소스 — 실제로 읽히는 파일의 경로 — 와 매칭되는 Condition입니다. match resource(!=!)로 인해 webpack이 다른 경로의 규칙을 적용하게 된 경우에만 Rule.resource와 다르며, 이때 resource는 가장된 경로이고 realResource는 디스크의 실제 파일입니다.
Rule.resourceFragment
요청의 fragment — 즉 # 이후의 모든 것 — 와 매칭되는 Condition입니다. import Foo from './foo.svg#icon'에서 fragment는 #icon입니다:
webpack.config.js
export default {
// ...
module: {
rules: [
{
test: /\.svg$/,
resourceFragment: /^#icon$/,
type: "asset/inline",
},
],
},
};Rule.descriptionData
모듈의 description 파일(일반적으로 가장 가까운 package.json) 내용과 매칭되는 Condition 집합입니다. 각 키는 테스트할 속성을 지정하며, 중첩된 속성은 점으로 구분된 키로 지정합니다:
webpack.config.js
export default {
// ...
module: {
rules: [
{
descriptionData: {
type: "module",
},
// ...
},
],
},
};Rule.descriptionRelativePath와 마찬가지로, match resource가 resource를 대체한 경우에는 조건이 적용되지 않습니다.
Rule.dependency
모듈을 요청한 dependency의 타입과 매칭되는 Condition으로, 규칙이 동일한 파일을 import된 방식에 따라 다르게 처리할 수 있게 합니다. webpack이 사용하는 값에는 import에 대한 'esm', require()에 대한 'commonjs', new URL()에 대한 'url', worker 생성자에 대한 'worker', 'amd', 'css-import', 'unknown'이 포함됩니다.
webpack.config.js
export default {
// ...
module: {
rules: [
{
test: /\.css$/,
dependency: "url",
type: "asset/resource",
},
],
},
};Rule.phase
dependency의 import phase와 매칭되는 Condition입니다: 일반 import에는 'evaluation', import defer에는 'defer', import source에는 'source'입니다.
Rule.resourceQuery
리소스 쿼리와 일치하는 Condition입니다. 이 옵션은 요청 문자열의 쿼리 섹션에 대해 테스트하는 경우 사용됩니다(즉, 물음표부터). import Foo from './foo.css?inline'을 사용하는 경우 다음 조건이 일치합니다.
webpack.config.js
export default {
// ...
module: {
rules: [
{
test: /\.css$/,
resourceQuery: /inline/,
type: "asset/inline",
},
],
},
};Rule.parser.parse
(input: string) => Buffer | JsonValue
Rule.type이 'json'으로 설정되면 Rules.parser.parse 옵션은 모듈의 소스를 파싱하여 JavaScript object로 변환하는 커스텀 로직을 구현하는 함수가 될 수 있습니다. 기본값은 JSON.parse입니다. 특정 loader 없이 toml, yaml 및 기타 JSON이 아닌 파일을 JSON으로 import할 때 유용할 수 있습니다:
webpack.config.js
import toml from "toml";
export default {
// ...
module: {
rules: [
{
test: /\.toml/,
type: "json",
parser: {
parse: toml.parse,
},
},
],
},
};위의 type: 'json'은 불필요하지 않으며, webpack이 이를 가정할 수 없습니다. Rule.parser는 규칙이 선택하는 모듈 타입의 파서에 전달되며, Rule.type만이 해당 타입을 선택합니다. 기본적으로 .json 파일과 application/json MIME 타입의 모듈만 'json' 타입이므로, .toml 파일은 그렇지 않으면 JavaScript로 파싱되어 parse 함수가 실행되지 않습니다.
모든 모듈 타입은 자체 스키마에 따라 주어진 parser 옵션을 검증하므로, parse는 해당 옵션이 없는 타입에는 적용되지 않습니다. 예를 들어 type: 'asset'의 경우 빌드가 parser has an unknown property 'parse' 오류와 함께 실패합니다.
Rule.rules
Rule이 일치 할 때도 사용되는 Rules의 배열입니다.
Rule.scheme
사용된 스키마(예: data, http)와 일치시키세요.
- Type:
string | RegExp | ((value: string) => boolean) | RuleSetLogicalConditions | RuleSetCondition[] - Available: 5.38.0+
webpack.config.js
export default {
module: {
rules: [
{
scheme: "data",
type: "asset/resource",
},
],
},
};Rule.sideEffects
bool
모듈의 어떤 부분에 부작용이 있는지 표시하세요. 자세한 내용은 Tree Shaking을 참고하세요.
Rule.test
테스트를 통과하는 모든 모듈을 포함합니다. Rule.test 옵션을 제공하면 Rule.resource도 제공 할 수 없습니다. 자세한 내용은 Rule.resource 및 Condition를 참고하세요.
Rule.type
string
가능한 변수: 'javascript/auto' | 'javascript/dynamic' | 'javascript/esm' | 'json' | 'webassembly/sync' | 'webassembly/async' | 'asset' | 'asset/source' | 'asset/resource' | 'asset/inline' | 'asset/bytes' | 'css' | 'css/auto' | 'css/module' | 'css/global'
Rule.type은 일치하는 모듈의 유형을 설정합니다. 이는 defaultRules 및 기본값 import 동작이 발생하지 않습니다. 예를 들어 커스텀 로더를 통해 .json파일을 로드하려면 type을 javascript/auto로 설정하여 webpack에 내장된 json import를 우회해야합니다.
webpack.config.js
export default {
// ...
module: {
rules: [
// ...
{
test: /\.json$/,
type: "javascript/auto",
loader: "custom-json-loader",
},
],
},
};
asset*유형에 대한 자세한 내용은 애셋 모듈 가이드를 참고하세요.
css/auto
5.87.0+css/auto 모듈 유형의 사용 사례는 여기를 참고하세요. css/auto를 사용하려면 experiments.css를 활성화해야 합니다.
export default {
target: "web",
mode: "development",
experiments: {
css: true,
},
module: {
rules: [
{
test: /\.less$/,
use: "less-loader",
type: "css/auto",
},
],
},
};Rule.use
UseEntry UseEntry[] (info: UseEntryInfo) => UseEntry | UseEntry[]
Webpack 5.87.0부터 undefined null과 같은 falsy 값을 사용하여 조건부로 특정 사용 항목을 비활성화할 수 있습니다.
UseEntry[]
Rule.use는 모듈에 적용되는 UseEntry의 배열일 수 있습니다.
문자열을 전달하는 use: [ 'sass-loader' ]는 loader property를 사용하는 use: [ { loader: 'sass-loader' } ]의 shorthand입니다.
로더는 여러 로더를 전달하여 연결될 수 있으며, 이는 오른쪽에서 왼쪽으로, 마지막 설정에서 첫 번째 설정 순서로 적용됩니다.
webpack.config.js
export default {
// ...
module: {
rules: [
{
// ...
use: [
"postcss-loader",
{
loader: "less-loader",
options: {
noIeCompat: true,
},
},
],
type: "css/auto",
},
],
},
};(info: UseEntryInfo) => UseEntry | UseEntry[]
Rule.use는 로드되는 모듈을 설명하는 객체를 받아 UseEntry 항목의 배열을 반환해야 하는 함수가 될 수도 있습니다.
info 파라미터(UseEntryInfo)에는 다음 필드가 있습니다:
compiler(string | undefined): 현재 child compiler의 이름, child compiler 외부에서는undefinedissuer(string): 로드되는 모듈을 import하는 모듈의 경로realResource(string | undefined): 항상 로드되는 모듈의 경로resource(string | undefined): 로드되는 모듈의 경로, 요청 문자열에서!=!로 리소스 이름이 덮어쓰여지지 않는 한 일반적으로realResource와 동일
반환 값에도 배열과 같은 shorthand를 사용할 수 있습니다(예: use: [ 'sass-loader' ]).
webpack.config.js
export default {
// ...
module: {
rules: [
{
use: (info) => [
{
loader: "custom-svg-loader",
},
{
loader: "svgo-loader",
options: {
plugins: [
{
cleanupIDs: {
prefix: basename(info.resource),
},
},
],
},
},
],
},
],
},
};자세한 정보는 UseEntry를 참고하세요.
Rule.resolve
모듈 계층에서 해석에 대한 설정을 할 수 있습니다. 해설 설정 페이지에서 가능한 모든 옵션을 참고하세요. 적용된 모든 해석 옵션은 상위 계층의 해석 옵션과 병합됩니다.
병합은 프로퍼티 단위로 이루어집니다: 객체는 상위 객체와 병합되는 반면, 배열은 상위 배열을 대체합니다. 배치한 위치에서 외부 값을 유지하려면 "..." 항목을 사용하세요 — 최상위 레벨에서 resolve.extensions 및 다른 배열 옵션이 사용하는 것과 동일한 규칙입니다. Rule.parser도 같은 방식으로 병합되며, loader에서 this.getResolve(options)에 전달되는 옵션도 마찬가지입니다.
export default {
module: {
rules: [
{
test: /\.txt$/,
resolve: {
// only .txt and .md are tried here, the outer extensions are dropped
extensions: [".txt", ".md"],
},
},
{
test: /\.mdx$/,
resolve: {
// .mdx is tried first, then whatever the outer config had
extensions: [".mdx", "..."],
},
},
],
},
};예를 들어, 모듈 레벨 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
export default {
resolve: {
alias: {
footer: "./footer/default.js",
},
},
};이 설정으로 번들을 생성하면 console.log(footer)는 'default footer'를 출력합니다. .js파일에 대한 Rule.resolve를 설정하고 footer 별칭을 overridden.js로 설정해보겠습니다.
webpack.js.org
export default {
resolve: {
alias: {
footer: "./footer/default.js",
},
},
module: {
rules: [
{
resolve: {
alias: {
footer: "./footer/overridden.js",
},
},
},
],
},
};변경된 설정으로 번들을 생성하면 console.log(footer)는 'overridden footer'를 출력합니다.
resolve.fullySpecified
boolean = true
활성화되면 .mjs 파일 또는 다른 .js 파일에서 모듈을 import할 때 가장 가까운 상위 package.json파일에 "type"필드가 "module"을 값으로 가지고 있는 경우 파일 확장자를 제공해야합니다. 그렇지 않으면 webpack이 Module not found 오류와 함께 컴파일에 실패합니다. 그리고 webpack은 resolve.mainFiles에 정의된 파일 이름으로 디렉터리를 확인하지 않으므로 파일 이름을 직접 지정해야합니다.
webpack.config.js
export default {
// ...
module: {
rules: [
{
test: /\.m?js$/,
resolve: {
fullySpecified: false, // 비활성화
},
},
],
},
};Rule.with
v5.92.0+with 키워드로 제공된 특정 조건에 따라 가져오기를 일치시킬 수 있는 조건을 통해 콘텐츠 유형에 따라 다른 규칙을 적용할 수 있습니다.
webpack.config.js
export default {
// ...
module: {
rules: [
{
// "with { type: 'json' }" 조건으로 가져오기를 처리합니다.
with: { type: "json" },
loader: import.meta.resolve("./loader-assert.js"),
},
],
},
};index.js
import one from "./pkg-1.json" with { type: "json" };이 예에서 Rule.with는 with { type: "json" } 조건으로 가져온 모든 모듈에 loader-assert.js를 적용하는 데 사용됩니다.
Condition
Condition은 아래 항목중의 하나가 됩니다.
- 문자열: 입력을 일치시키려면 제공된 문자열로 시작해야 합니다. 예를 들면, 절대 디렉터리 경로 또는 파일의 절대 경로입니다.
- 정규표현식: 입력을 검사합니다.
- 함수: 입력과 함께 호출되며 일치하려면 참과 같은 값을 반환해야 합니다.
- Condition 배열: Condition 중 하나 이상이 일치해야 합니다.
- 객체: 모든 프로퍼티가 일치해야 합니다. 각 속성에는 정의 된 동작이 있습니다.
{ and: [Condition] }: 모든 Condition이 일치해야 합니다.
{ or: [Condition] }: 어떤 Condition이든 일치하면 됩니다.
{ not: [Condition] }: 모든 Condition이 일치하면 안 됩니다.
{ glob: string | [string] }: 5.110.0+ 입력이 glob pattern 중 하나와 일치해야 합니다. pattern 문법은 Rule.glob을 참고하세요.
조건이 테스트되는 입력은 어떤 필드에 작성되었는지에 따라 다릅니다: test, include, exclude는 모두 모듈의 resource 경로를 받고, issuer는 이를 요청한 모듈의 경로, resourceQuery는 쿼리 문자열을 받습니다. 문법은 모든 곳에서 동일합니다.
조건은 조합됩니다. 단순 배열은 or이므로 test: [/\.ts$/, /\.tsx$/]와 test: { or: [/\.ts$/, /\.tsx$/] }는 동일한 모듈과 매칭되며, 하나의 객체의 프로퍼티는 and로 결합됩니다. 다음 조건은 src/ 아래의 TypeScript 파일 중 테스트 파일이 아닌 것과 매칭됩니다 — 세 가지 프로퍼티가 모두 충족되어야 하며, not은 자체 조건을 취하므로 두 개의 정규표현식을 나열하면 둘 중 하나에 매칭되는 파일을 제외합니다:
import path from "node:path";
import { fileURLToPath } from "node:url";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
export default {
// ...
module: {
rules: [
{
test: {
// every property of this object must match, so:
and: [
// the path must start with `<context>/src`
path.resolve(__dirname, "src"),
// and end with `.ts` or `.tsx` (an array is an `or`)
[/\.ts$/, /\.tsx$/],
],
// and match neither of these
not: [/\.test\.tsx?$/, /\.stories\.tsx?$/],
},
loader: "ts-loader",
},
],
},
};Example:
import path from "node:path";
import { fileURLToPath } from "node:url";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
export default {
// ...
module: {
rules: [
{
test: /\.css$/,
include: [
// `app/styles`로 시작하는 현재 디렉터리와 관련된 모든 경로를 포함합니다.
// 예. `app/styles.css`, `app/styles/styles.css`, `app/stylesheet.css`
path.resolve(__dirname, "app/styles"),
// `vendor/styles/` 디렉터리의 내용만 포함하도록 슬래시를 추가합니다.
path.join(__dirname, "vendor/styles/"),
],
},
],
},
};UseEntry
object (info: UseEntryInfo) => UseEntry
object
문자열인 loader 프로퍼티가 있어야 합니다. 로더 해석 옵션(resolveLoader)을 사용하여 설정 context에 상대적으로 해석됩니다.
options 프로퍼티는 문자열이나 객체가 될 수 있습니다. 이 값은 로더에 전달되며 로더 옵션으로 해석되어야 합니다.
webpack은 리소스와 옵션을 포함한 모든 loader로부터 고유한 모듈 식별자를 생성해야 합니다. 이를 위해 options 객체를 JSON.stringify합니다. 99.9%의 경우에는 문제없지만, 동일한 loader를 다른 옵션으로 리소스에 적용하고 옵션의 문자열화된 값이 동일한 경우 고유하지 않을 수 있습니다.
순환 JSON 같은 옵션 객체를 문자열화 할 수 없는 경우에도 중단됩니다. 이를 해결하기 위해 고유 식별자로 사용되는 옵션 객체에서 ident 속성을 가질 수 있습니다.
webpack.config.js
export default {
// ...
module: {
rules: [
{
loader: "sass-loader",
options: {
sourceMap: true,
},
},
],
},
};(info: UseEntryInfo) => UseEntry
UseEntry는 로드되는 모듈을 설명하는 객체를 받아 함수가 아닌 UseEntry 객체를 반환해야 하는 함수가 될 수도 있습니다. 이를 사용하여 모듈별로 loader 옵션을 다르게 적용할 수 있습니다.
info 파라미터(UseEntryInfo)에는 다음 필드가 있습니다:
compiler(string | undefined): 현재 child compiler의 이름, child compiler 외부에서는undefinedissuer(string): 로드되는 모듈을 import하는 모듈의 경로realResource(string | undefined): 항상 로드되는 모듈의 경로resource(string | undefined): 로드되는 모듈의 경로, 요청 문자열에서!=!로 리소스 이름이 덮어쓰여지지 않는 한 일반적으로realResource와 동일
webpack.config.js
export default {
// ...
module: {
rules: [
{
test: /\.svg$/,
type: "asset",
use: (info) => ({
loader: "svgo-loader",
options: {
plugins: [
{
cleanupIDs: { prefix: basename(info.resource) },
},
],
},
}),
},
],
},
};Module Contexts
이 옵션은 동적 종속성이 발생할 때 생성되는 컨텍스트의 기본 설정을 설명합니다.
unknown 동적 종속성 의 예시: require.
expr 동적 종속성 의 예시: require(expr).
wrapped 동적 종속성 의 예시: require('./templates/' + expr).
동일한 설정이 동등한 import() 호출에도 적용되므로, exprContextRegExp는 완전히 동적인 import(expr)가 어떤 모듈을 가져오는지 결정합니다. 기본값에서 어떤 일이 발생하는지는 import()의 동적 표현식을 참고하세요.
이 옵션들은 module.parser.javascript 아래에 있습니다. 다음은 기본값과 함께 나열한 것입니다:
webpack.config.js
export default {
// ...
module: {
parser: {
javascript: {
exprContextCritical: true,
exprContextRecursive: true,
exprContextRegExp: false,
exprContextRequest: ".",
unknownContextCritical: true,
unknownContextRecursive: true,
unknownContextRegExp: false,
unknownContextRequest: ".",
wrappedContextCritical: false,
wrappedContextRecursive: true,
wrappedContextRegExp: /.*/,
},
},
},
};다음은 몇 가지 사용 사례입니다.
- Warn for dynamic dependencies:
wrappedContextCritical: true. require(expr)should include the whole directory:exprContextRegExp: /^\.\//require('./templates/' + expr)should not include subdirectories by default:wrappedContextRecursive: false- Set the inner regular expression for partial dynamic dependencies:
wrappedContextRegExp: /\.\*/