Module

이 옵션은 프로젝트 내에서 다른 유형의 모듈을 처리하는 방법을 결정합니다.

module.defaultRules

모듈에 기본적으로 적용되는 규칙의 배열입니다.

자세한 내용은 소스 코드를 참고하세요.

module.exports = {
  module: {
    defaultRules: [
      '...', // "..."를 사용하여 기본적으로 webpack에 의해 적용되는 규칙을 참조할 수 있습니다.
    ],
  },
};

Webpack 5.87.0부터 0, "", false, nullundefined를 포함한 falsy 값을 module.defaultRules로 전달하여 특정 규칙을 조건부로 비활성화할 수 있습니다.

module.exports = {
  module: {
    defaultRules: [
      false &&
        {
          // 이 규칙은 비활성화됩니다.
        },
    ],
  },
};

module.generator

5.12.0+

module.generator를 사용하여 한 곳에서 모든 제너레이터의 옵션을 설정할 수 있습니다.

webpack.config.js

module.exports = {
  module: {
    generator: {
      asset: {
        // asset 모듈 제너레이터 옵션

        // 데이터 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 모듈 제너레이터 옵션

        // 데이터 URL 제너레이터 옵션
        dataUrl: {
          // 애셋 인코딩(기본값은 "base64")
          // type: 'base64' | false
          encoding: 'base64',
          // 애셋 Mimetype (기본적으로 파일 확장자에서 가져옵니다).
          // type: string
          mimetype: 'image/png',
        },
      },
      'asset/resource': {
        // asset/resource 모듈 제너레이터 옵션

        // 이 애셋 모듈에서 출력 애셋을 내보냅니다. 예를 들어 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/',
      },
      javascript: {
        // 이 모듈 유형에는 아직 제너레이터 옵션이 지원되지 않습니다.
      },
      'javascript/auto': {
        // 위와 동일
      },
      'javascript/dynamic': {
        // 위와 동일
      },
      'javascript/esm': {
        // 위와 동일
      },
      // 그외 다른 옵션들…
    },
  },
};

module.parser

5.12.0+

module.generator처럼 module.parser를 사용하여 한 곳에서 모든 파서의 옵션을 설정할 수 있습니다.

webpack.config.js

module.exports = {
  module: {
    parser: {
      asset: {
        // asset 모듈 파서 옵션
      },
      'asset/inline': {
        // 이 모듈 유형에는 아직 파서 옵션이 지원되지 않습니다.
      },
      'asset/resource': {
        // 위와 동일
      },
      'asset/source': {
        // 위와 동일
      },
      javascript: {
        // javascript 모듈 파서 옵션
        // 예. require.ensure 구문 파싱 활성화
        requireEnsure: true,
      },
      'javascript/auto': {
        // 위와 동일
      },
      'javascript/dynamic': {
        // 위와 동일
      },
      'javascript/esm': {
        // 위와 동일
      },
      // 그외 다른 옵션들…
    },
  },
};

module.parser.javascript

JavaScript 파서를 위한 옵션을 설정할 수 있습니다.

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

Rule.parser에서 이러한 옵션을 설정하고 특정 모듈을 대상으로 지정할 수 있습니다.

module.parser.javascript.commonjsMagicComments

CommonJS를 위해 magic comments 지원을 활성화할 수 있습니다.

  • 타입: boolean

  • 가능한 버전: 5.17.0+

  • 예제:

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

webpackIgnore 주석만 지원됩니다.

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

module.parser.javascript.dynamicImportFetchPriority

동적 import를 위해 전역 fetchPriority를 지정합니다.

  • Type: 'low' | 'high' | 'auto' | false

  • Available: 5.87.0+

  • Example:

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

module.parser.javascript.dynamicImportMode

동적 import를 위한 전역 프리로드를 지정합니다.

  • Type: 'eager' | 'weak' | 'lazy' | 'lazy-once'

  • Available: 5.73.0+

  • Example:

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

module.parser.javascript.dynamicImportPrefetch

동적 import를 위한 전역 프리로드를 지정합니다.

  • Type: number | boolean

  • Available: 5.73.0+

  • Example:

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

module.parser.javascript.dynamicImportPreload

동적 import를 위한 전역 프리로드를 지정합니다.

  • Type: number | boolean

  • Available: 5.73.0+

  • Example:

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

module.parser.javascript.exportsPresence

\"import ... from ...\"\"export ... from ...\"에서 내보내기 이름이 잘못된 경우의 동작을 지정합니다.

  • Type: 'error' | 'warn' | 'auto' | false

  • Available: 5.62.0+

  • Example:

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

module.parser.javascript.importExportsPresence

\"import ... from ...\"에서 내보내기 이름이 잘못된 경우의 동작을 지정합니다.

  • Type: 'error' | 'warn' | 'auto' | false

  • Available: 5.62.0+

  • Example:

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

module.parser.javascript.importMeta

import.meta 평가를 활성화 또는 비활성화합니다.

  • Type: boolean = true

  • Available: 5.68.0+

  • Example:

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

module.parser.javascript.importMetaContext

import.meta.webpackContext 평가를 사용하거나 사용하지 않도록 설정합니다.

  • Type: boolean

  • Available: 5.70.0+

  • Example:

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

module.parser.javascript.reexportExportsPresence

\"export ... from ...\"에서 내보내기 이름이 잘못된 경우의 동작을 지정합니다. 이것은 TypeScript에서 타입을 다시 내보낼때 \"export ... from ...\"에서 \"export type ... from ...\"으로 마이그레이션하는 동안 비활성화하는 데 유용합니다.

  • Type: 'error' | 'warn' | 'auto' | false

  • Available: 5.62.0+

  • Example:

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

module.parser.javascript.url

new URL() 구문 파싱을 활성화합니다.

  • 타입: boolean = true | 'relative'

  • 예제:

    module.exports = {
      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" />
  1. 이것은 기준 URL이 서버에의 알려지지 않을 때 SSR(서버 사이드 렌더링)에 유용하며 몇 바이트를 절약할 수 있습니다. 동일하게 유지하기 위해서 클라이언트 빌드에서도 사용해야 합니다.
  2. 또한 서버 측 렌더링이 일반적으로 필요한 정적 사이트 생성기, mini-css-plugin 및 html-plugin 등을 위해서도 필요합니다.

module.noParse

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

webpack이 주어진 정규식과 일치하는 파일을 파싱하지 못하도록 합니다. 제외된 파일에는 import, require, define 또는 기타 import 메커니즘의 호출이 없어야 합니다. 이렇게 하면 큰 라이브러리를 무시할 때 빌드 성능을 향상 시킬 수 있습니다.

webpack.config.js

module.exports = {
  //...
  module: {
    noParse: /jquery|lodash/,
  },
};
module.exports = {
  //...
  module: {
    noParse: (content) => /jquery|lodash/.test(content),
  },
};

module.unsafeCache

boolean function (module)

모듈 요청에 대한 해석을 캐시합니다. module.unsafeCache에 대한 몇 가지 기본값이 있습니다.

  • cache가 비활성화되어 있다면 false
  • cache가 활성화되어 있고 모듈이 node 모듈에서 온 것으로 보인다면 true, 그렇지 않다면 false

webpack.config.js

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

module.rules

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

모듈이 생성 될 때 요청과 일치하는 Rule의 배열입니다. 이러한 규칙은 모듈 생성 방법을 수정할 수 있습니다. 로더를 모듈에 적용시키거나 파서를 수정할 수 있습니다.

Webpack 5.87.0부터 false, undefined, null0과 같은 falsy 값을 사용하여 조건부로 규칙을 비활성화할 수 있습니다.

Rule

object

Rule은 Conditions, Results 그리고 중첩된 Rules 세 부분으로 나눠질 수 있습니다.

Rule Conditions

conditions에 대한 두가지 입력 값이 있습니다.

  1. resource: 요청된 파일의 절대 경로입니다. resolve 규칙에 따라 이미 해석되었습니다.

  2. 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와 일치합니다.

여러 조건을 사용하는 경우, 모든 조건이 일치해야 합니다.

Rule results

Rule results는 Rule condition이 일치하는 경우에만 사용됩니다.

Rule에는 두 가지 출력 값이 있습니다.

  1. 적용된 로더: resource에 적용된 로더의 배열입니다.
  2. 파서 옵션: 모듈에 대한 파서를 만드는 데 사용해야하는 옵션 객체입니다.

loader, options, use 프로퍼티는 로더에 영향을 줍니다.

query, loaders 프로퍼티는 호환성을 위해 존재합니다.

enforce 프로퍼티는 일반, 사전 또는 사후 로더인지에 따라서 로더의 범주에 영향을 줍니다.

parser 프로퍼티는 파서 옵션에 영향을 줍니다.

Nested rules

중첩된 rules은 rules, oneOf 프로퍼티에서 지정할 수 있습니다.

이러한 rule은 상위 Rule condition이 일치하는 경우에만 평가됩니다. 각 중첩 rule은 자체적으로 조건을 포함 할 수 있습니다.

평가의 순서는 다음과 같습니다.

  1. 상위 rule
  2. rules
  3. oneOf

Rule.enforce

string

가능한 값: 'pre' | 'post'

로더의 범주를 지정합니다. 값이 없으면 일반 로더를 의미합니다.

추가적으로 import/require의 인라인으로 적용된 "인라인 로더"도 있습니다.

모든 로더가 차례로 통과하는 두 단계가 있습니다.

  1. Pitching 단계: 로더의 pitch 메소드는 post, inline, normal, pre 순서로 호출됩니다. 자세한 내용은 Pitching Loader를 참고하세요.
  2. 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.resourceCondition.exclude를 참고하세요.

Rule.include

조건과 일치하는 모든 모듈을 포함합니다. Rule.include 옵션을 사용하면 Rule.resource 옵션을 사용할 수 없습니다. 자세한 내용은 Rule.resourceCondition.include를 참고하세요.

Rule.issuer

요청한 모듈과 비교할 Condition입니다. 아래의 예제에서, a.jsissuerindex.js 파일의 경로입니다.

index.js

import A from './a.js';

이 옵션은 특정 모듈 또는 모듈 세트의 디펜던시에 로더를 적용하는 데 사용할 수 있습니다.

Rule.issuerLayer

issuer의 계층별로 필터링하고 일치시킬 수 있습니다.

webpack.config.js

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

Rule.layer

string

모듈이 배치되어야 하는 계층을 지정합니다. 모듈 그룹은 분할 청크, 통계 또는 엔트리 옵션에서 사용할 수 있는 하나의 레이어로 통합될 수 있습니다.

webpack.config.js

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

Rule.loader

Rule.loaderRule.use: [ { loader } ]의 단축어입니다. 자세한 내용은 Rule.useUseEntry.loader를 참고하세요.

Rule.loaders

Rule.loadersRule.use의 별칭입니다. 자세한 내용은 Rule.use를 참고하세요.

Rule.mimetype

mimetype을 사용하여 설정 규칙을 데이터 URI에 일치시킬 수 있습니다.

webpack.config.js

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

application/json, text/javascript, application/javascript, application/nodeapplication/wasm은 이미 기본적인 mimetype으로 포함되어 있습니다.

Rule.oneOf

Rule이 일치할 때 첫 번째 일치하는 Rule만 사용되는 Rules의 배열입니다.

webpack.config.js

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

Rule.options / Rule.query

Rule.optionsRule.queryRule.use: [ { options } ]의 단축어입니다. 자세한 내용은 Rule.useUseEntry.options을 참고하세요.

Rule.parser

파서 옵션이 있는 객체입니다. 적용된 모든 파서 옵션이 병합됩니다.

파서는 이러한 옵션을 검사하고 그에 따라 자체적으로 비활성화하거나 재구성할 수 있습니다. 대부분의 기본 플러그인은 값을 다음과 같이 해석합니다.

  • 옵션을 false로 설정하면 파서가 비활성화됩니다.
  • 옵션을 true로 설정하거나 undefined로 두면 파서가 활성화됩니다.

그러나, 파서 플러그인은 boolean 이상의 값을 받아들일 수 있습니다. 예를 들면, 내부의 NodeStuffPlugintrue 대신에 객체를 받아 특정 Rule에 대한 옵션을 추가할 수 있습니다.

예제 (기본 플러그인의 파서 옵션):

module.exports = {
  //...
  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.* 비활성화
          node: false, // __dirname, __filename, module, require.extensions, require.main, 등 비활성화
          commonjsMagicComments: false, // CommonJS를 위한 magic comments 지원 비활성화
          node: {}, // 모듈 수준에서 [node](/configuration/node) 계층 재구성
          worker: ['default from web-worker', '...'], // javascript 파일에 대한 WebWorker 처리를 커스터마이즈합니다. "..."는 기본값을 나타냅니다.
        },
      },
    ],
  },
};

Rule.typeasset이면 Rules.parser 옵션은 파일 내용을 Base64로 인코딩할지 또는 별도의 파일로 출력 디렉터리에 내보낼 지 여부를 나타내는 조건을 설명하는 객체 또는 함수일 수 있습니다.

Rule.typeasset 또는 asset/inline인 경우 Rule.generator옵션은 모듈 소스의 인코딩을 설명하는 객체이거나 사용자 지정 알고리즘으로 모듈의 소스를 인코딩하는 함수일 수 있습니다.

추가적인 정보나 사용 사례를 위해 애셋 모듈 가이드를 참고하세요.

Rule.parser.dataUrlCondition

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

모듈 소스 크기가 maxSize보다 작으면 모듈이 Base64 인코딩 문자열로 번들에 삽입되고, 그렇지 않으면 모듈 파일이 출력 디렉터리로 내보내집니다.

webpack.config.js

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

함수를 dataUrlCondition의 값으로 설정한 경우에는 true를 반환하면 webpack이 모듈을 Base64 인코딩 문자열로 번들에 삽입하도록 지시합니다. 그렇지 않으면 모듈 파일이 출력 디렉터리로 내보내집니다.

webpack.config.js

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

Rule.generator

Rule.generator.dataUrl

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

Rule.generator.dataUrl이 객체로 사용되면 두개의 프로퍼티를 설정할 수 있습니다.

  • encoding: 'base64'로 설정하면 모듈 소스는 Base64 알고리즘을 사용하여 인코딩됩니다. encoding을 false로 설정하면 인코딩이 비활성화됩니다.
  • mimetype: 데이터 URI의 MIME 유형입니다. 기본적으로 모듈 리소스 확장에서 확인합니다.

webpack.config.js

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

함수로 사용하면 모든 모듈에 대해 실행되며 데이터 URI 문자열을 반환해야 합니다.

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

Rule.generator.emit

애셋 모듈에서 애셋 쓰기를 하지 않는 경우, 서버 사이드 랜더링에서 사용할 수 있습니다.

  • Type: boolean = true

  • Available: 5.25.0+

  • Example:

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

Rule.generator.filename

output.assetModuleFilename과 동일하지만 특정 규칙에 사용됩니다. output.assetModuleFilename을 재정의하고 assetasset/resource 모듈 유형에서만 작동합니다.

webpack.config.js

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

Rule.generator.publicPath

특정 애셋 모듈에 대해 publicPath를 사용자 지정합니다.

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

Rule.generator.outputPath

'output.path'를 기준으로 지정된 폴더의 애셋을 내보냅니다. 사용자 지정 'publicPath'가 폴더 구조와 일치하도록 지정된 경우에만 필요합니다.

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

Rule.resource

리소스와 일치하는 Condition입니다. 자세한 내용은 규칙 조건을 참고하세요.

Rule.resourceQuery

리소스 쿼리와 일치하는 Condition입니다. 이 옵션은 요청 문자열의 쿼리 섹션에 대해 테스트하는 경우 사용됩니다(즉, 물음표부터). import Foo from './foo.css?inline'을 사용하는 경우 다음 조건이 일치합니다.

webpack.config.js

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

Rule.parser.parse

function(input) => string | object

Rule.type'json'으로 설정된 경우 Rules.parser.parse옵션은 모듈의 소스를 구문 분석하고 이를 JavaScript 객체로 변환하는 커스텀 로직을 구현하는 함수일 수 있습니다. 특정 로더없이 toml, yaml 및 기타 JSON이 아닌 파일을 JSON으로 가져 오는 것이 유용할 수 있습니다.

webpack.config.js

const toml = require('toml');

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

Rule.rules

Rule이 일치 할 때도 사용되는 Rules의 배열입니다.

Rule.sideEffects

bool

모듈의 어떤 부분에 부작용이 있는지 표시하세요. 자세한 내용은 Tree Shaking을 참고하세요.

Rule.test

테스트를 통과하는 모든 모듈을 포함합니다. Rule.test 옵션을 제공하면 Rule.resource도 제공 할 수 없습니다. 자세한 내용은 Rule.resourceCondition를 참고하세요.

Rule.type

string

가능한 변수: 'javascript/auto' | 'javascript/dynamic' | 'javascript/esm' | 'json' | 'webassembly/sync' | 'webassembly/async' | 'asset' | 'asset/source' | 'asset/resource' | 'asset/inline' | 'css/auto'

Rule.type은 일치하는 모듈의 유형을 설정합니다. 이는 defaultRules 및 기본값 import 동작이 발생하지 않습니다. 예를 들어 커스텀 로더를 통해 .json파일을 로드하려면 typejavascript/auto로 설정하여 webpack에 내장된 json import를 우회해야합니다.

webpack.config.js

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

asset* 유형에 대한 자세한 내용은 애셋 모듈 가이드를 참고하세요.

css/auto

5.87.0+

css/auto 모듈 유형의 사용 사례는 여기를 참고하세요. css/auto를 사용하려면 experiments.css를 활성화해야 합니다.

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

Rule.use

[UseEntry] function(info)

Webpack 5.87.0부터 undefined null과 같은 falsy 값을 사용하여 조건부로 특정 사용 항목을 비활성화할 수 있습니다.

[UseEntry]

Rule.use는 모듈에 적용되는 UseEntry의 배열일 수 있습니다.

use: [ 'style-loader' ] 같이 string을 전달하는 것은 use: [ { loader: 'style-loader '} ] 같이 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를 참고하세요.

Rule.resolve

모듈 계층에서 해석에 대한 설정을 할 수 있습니다. 해설 설정 페이지에서 가능한 모든 옵션을 참고하세요. 적용된 모든 해석 옵션은 상위 계층의 해석 옵션과 병합됩니다.

예를 들면, 모듈 계층 해석을 보여주기 위해 ./src/index.js, ./src/footer/default.js./src/footer/overridden.js 엔트리가 있다고 가정하겠습니다.

./src/index.js

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

./src/footer/default.js

export default 'default footer';

./src/footer/overridden.js

export default 'overridden footer';

webpack.js.org

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

이 설정으로 번들을 생성하면 console.log(footer)는 'default footer'를 출력합니다. .js파일에 대한 Rule.resolve를 설정하고 footer 별칭을 overridden.js로 설정해보겠습니다.

webpack.js.org

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

변경된 설정으로 번들을 생성하면 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

module.exports = {
  // ...
  module: {
    rules: [
      {
        test: /\.m?js$/,
        resolve: {
          fullySpecified: false, // 비활성화
        },
      },
    ],
  },
};

Condition

Condition은 아래 항목중의 하나가 됩니다.

  • 문자열: 입력을 일치시키려면 제공된 문자열로 시작해야 합니다. 예를 들면, 절대 디렉터리 경로 또는 파일의 절대 경로입니다.
  • 정규표현식: 입력을 검사합니다.
  • 함수: 입력과 함께 호출되며 일치하려면 참과 같은 값을 반환해야 합니다.
  • Condition 배열: Condition 중 하나 이상이 일치해야 합니다.
  • 객체: 모든 프로퍼티가 일치해야 합니다. 각 속성에는 정의 된 동작이 있습니다.

{ and: [Condition] }: 모든 Condition이 일치해야 합니다.

{ or: [Condition] }: 어떤 Condition이든 일치하면 됩니다.

{ not: [Condition] }: 모든 Condition이 일치하면 안 됩니다.

Example:

const path = require('path');

module.exports = {
  //...
  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 function(info)

object

문자열인 loader 프로퍼티가 있어야 합니다. 로더 해석 옵션(resolveLoader)을 사용하여 설정 context에 상대적으로 해석됩니다.

options 프로퍼티는 문자열이나 객체가 될 수 있습니다. 이 값은 로더에 전달되며 로더 옵션으로 해석되어야 합니다.

호환성을 위해 options 프로퍼티의 별칭인 query 속성도 가능합니다. options 프로퍼티를 사용하는 것을 권장합니다.

webpack은 옵션을 포함한 모든 로더와 리소스에서 고유한 모듈 식별자를 생성해야합니다. 옵션 객체의 JSON.stringify로 이를 시도합니다. 99.9%의 경우에 문제가 없지만 리소스에 다른 옵션이 있는 동일한 로더를 적용하고 옵션에 일부 문자열 값이 있는 경우 고유하지 않을 수 있습니다.

순환 JSON 같은 옵션 객체를 문자열화 할 수 없는 경우에도 중단됩니다. 이를 해결하기 위해 고유 식별자로 사용되는 옵션 객체에서 ident 속성을 가질 수 있습니다.

webpack.config.js

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

function(info)

UseEntry는 로드되는 모듈을 나타내는 객체를 인수로 받는 함수일 수도 있으며 함수가 아닌 UseEntry 객체를 반환해야 합니다.

info 객체 파라미터에는 다음과 같은 필드가 있습니다.

  • compiler: 현재 webpack 컴파일러 (정의되지 않을 수 있음)
  • 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) },
              },
            ],
          },
        }),
      },
    ],
  },
};

Module Contexts

이 옵션은 동적 종속성이 발생할 때 생성되는 컨텍스트의 기본 설정을 설명합니다.

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는 export가 누락되면 경고 대신 오류를 발생시킵니다.
  • 부분적 동적 종속성에 대한 내부 정규식 설정(wrappedContextRegExp: /\\.\\*/)

20 Contributors

sokraskipjackjouni-kantolajhnnsdylanonelsonbyzykpnevaresfadysamirsadeknerdkid93EugeneHlushkosuperburritolukasgeiterskovysmelukovopl-Mistyyyyanshumanvchenxsansnitin315vabushkevich

Translators