Externals
externals 옵션은 출력 번들에서 의존성을 제외하는 방법을 제공합니다. 대신, 생성된 번들은 소비자(모든 최종 사용자 애플리케이션)의 환경에 존재하기 위해 해당 의존성에 의존합니다. 이 기능은 일반적으로 라이브러리 개발자에게 가장 유용하지만, 이것을 위한 다양한 애플리케이션이 있습니다.
externals
string object function RegExp [string, object, function, RegExp]
특정 import 된 패키지의 번들링을 방지하고 대신 런타임에 이러한 외부 종속성을 검색합니다.
예를 들어, 번들링 대신 CDN에서 jQuery를 포함하려면 다음을 수행해야 합니다.
index.html
<script
src="https://code.jquery.com/jquery-3.1.0.js"
integrity="sha256-slogkvB1K3VOkzAI8QITxV3VzpOnkeNVsKvtkYLMjfk="
crossorigin="anonymous"
></script>webpack.config.js
module.exports = {
// ...
externals: {
jquery: "jQuery",
},
};이렇게 하면 종속 모듈이 변경되지 않습니다. 즉, 아래 표시된 코드가 계속 작동합니다.
import $ from "jquery";
$(".my-element").animate(/* ... */);위의 webpack.config.js에서 externals에 지정된 속성 이름 jquery는 import $ from 'jquery'의 모듈인 jquery가 번들링에서 제외되어야 함을 나타냅니다. 기본 외부 라이브러리 유형이 var이므로 이 모듈을 대체하기 위해 jQuery값이 전역 jQuery변수를 검색하는 데 사용됩니다. externalsType를 참고하세요.
위에서는 외부 전역 변수를 사용하는 예를 보여주었지만, 실제로 외부 속성에는 전역변수, CommonJS, AMD, ES2015 모듈과 같은 형식으로 사용할 수 있습니다. 자세한 내용은 externalsType을 참고하세요.
string
externalsType에 따라 전역 변수('global', 'this', 'var', 'window')의 이름이 될 수 있습니다. 또는 모듈 이름 (amd, commonjs, module, umd)을 참고하세요.
1개의 외부 속성만 정의하는 경우에도 축약된 구문을 사용할 수 있습니다.
module.exports = {
// ...
externals: "jquery",
};이는 아래와 동일합니다.
module.exports = {
// ...
externals: {
jquery: "jquery",
},
};${externalsType} ${libraryName} 구문을 사용하여 외부에 외부 라이브러리 유형을 지정할 수 있습니다. 이는 externalsType옵션에 지정된 기본 외부 라이브러리 유형을 재정의합니다.
예를들어 외부 라이브러리가 CommonJS 모듈인 경우, 다음과 같이 지정할 수 있습니다.
module.exports = {
// ...
externals: {
jquery: "commonjs jquery",
},
};[string]
module.exports = {
// ...
externals: {
subtract: ["./math", "subtract"],
},
};subtract: ['./math', 'subtract']를 사용하면 모듈의 일부를 선택할 수 있습니다. 여기서 ./math는 모듈이고, 번들은 subtract 변수에 지정된 부분만 필요로 합니다.
externalsType이 commonjs인 경우 이 예제는 require('./math').subtract;로 번역되고, externalsType이 window인 경우 이 예제는 window["./math"]["subtract"];로 번역됩니다.
문자열 구문(#string)과 유사하게, 배열의 첫 번째 항목에 ${externalsType} ${libraryName} 구문을 사용하여 외부 라이브러리 유형을 지정할 수 있습니다. 예를 들면 다음과 같습니다.
module.exports = {
// ...
externals: {
subtract: ["commonjs ./math", "subtract"],
},
};object
module.exports = {
// ...
// 또는
externals: {
react: "react",
},
};module.exports = {
// ...
// or
externals: {
lodash: {
commonjs: "lodash",
amd: "lodash",
root: "_", // 전역 변수를 나타냅니다.
},
},
};module.exports = {
// ...
// 또는
externals: {
subtract: {
root: ["math", "subtract"],
},
},
};이 구문은 외부 라이브러리를 사용할 수 있는 모든 가능한 방법을 설명하는 데 사용됩니다. 여기서 lodash는 AMD 및 CommonJS 모듈 시스템에서 lodash로 사용할 수 있지만 전역 변수 형식에서는 _로 사용할 수 있습니다. 여기서 subtract는 전역 math 객체 아래의 subtract 속성을 통해 사용할 수 있습니다. (예. window['math']['subtract'])
function
function ({ context, request, contextInfo, getResolve }, callback)function ({ context, request, contextInfo, getResolve }) => promise5.15.0+
webpack에서 외부화하려는 동작을 제어하기 위해 자체 함수를 정의하는 것이 유용할 수 있습니다. 예를 들어 webpack-node-externals는, node_modules 디렉터리에서 모든 모듈을 제외하고 패키지를 허용 목록에 추가하는 옵션을 제공합니다.
함수가 받을 수 있는 인수는 다음과 같습니다.
ctx(object): 파일 세부 정보를 포함하는 객체입니다.ctx.context(string): import를 포함하는 파일의 디렉터리입니다.ctx.request(string): 요청 중인 import 경로입니다.ctx.contextInfo(object): issuer(예. 레이어, 컴파일)에 대한 정보를 포함합니다.ctx.getResolve5.15.0+: 현재 리졸브 옵션으로 리졸브 함수 가져오기.
callback(function (err, result, type)): 모듈을 외부화하는 방법을 나타내는 데 사용되는 콜백 함수입니다.
콜백 함수는 세 가지 인수를 사용합니다.
err(Error): import를 외부화하는 동안 오류가 있었는지 나타내는 데 사용됩니다. 오류가 있는 경우 이 파라미터만 사용해야 합니다.result(string[string]object): 다른 외부 형식(string,[string], 또는object)를 사용하여 외부 모듈을 설명합니다.type(string): 모듈 external type을 나타내는 선택적 파라미터입니다(result파라미터에 아직 표시되지 않은 경우).
예를들어, import 경로가 정규 표현식과 일치하는 모든 import를 외부화 하려면 다음을 수행할 수 있습니다.
webpack.config.js
module.exports = {
// ...
externals: [
function ({ context, request }, callback) {
if (/^yourregex$/.test(request)) {
// 요청 경로를 사용하여 commonjs 모듈로 외부화
return callback(null, `commonjs ${request}`);
}
// import를 외부화하지 않고 계속
callback();
},
],
};다른 모듈 형식을 사용하는 다른 예제입니다.
webpack.config.js
module.exports = {
externals: [
function (ctx, callback) {
// external은 `@scope/library`에 있는 `commonjs2` 모듈입니다.
callback(null, "@scope/library", "commonjs2");
},
],
};webpack.config.js
module.exports = {
externals: [
function (ctx, callback) {
// external은 `nameOfGlobal`이라는 전역 변수입니다.
callback(null, "nameOfGlobal");
},
],
};webpack.config.js
module.exports = {
externals: [
function (ctx, callback) {
// external은 `@scope/library` 모듈에서 명명된 export입니다.
callback(null, ["@scope/library", "namedexport"], "commonjs");
},
],
};webpack.config.js
module.exports = {
externals: [
function (ctx, callback) {
// external은 UMD 모듈입니다.
callback(null, {
root: "componentsGlobal",
commonjs: "@scope/components",
commonjs2: "@scope/components",
amd: "components",
});
},
],
};RegExp
주어진 정규식과 일치하는 모든 의존성은 출력 번들에서 제외됩니다.
webpack.config.js
module.exports = {
// ...
externals: /^(jquery|\$)$/i,
};이 경우, jQuery, 대문자 여부, 또는 $라는 종속성이 외부화됩니다.
Combining syntaxes
때때로 위의 구문을 조합하여 사용할 수 있습니다. 다음과 같은 방식으로 수행할 수 있습니다.
webpack.config.js
module.exports = {
// ...
externals: [
{
// String
react: "react",
// Object
lodash: {
commonjs: "lodash",
amd: "lodash",
root: "_", // 전역 변수를 나타냅니다.
},
// [string]
subtract: ["./math", "subtract"],
},
// Function
function ({ context, request }, callback) {
if (/^yourregex$/.test(request)) {
return callback(null, `commonjs ${request}`);
}
callback();
},
// Regex
/^(jquery|\$)$/i,
],
};이 설정을 사용하는 방법에 대한 자세한 내용은, 라이브러리 작성 방법에 대한 문서를 참고하십시오.
byLayer
function object
레이어별로 external을 지정합니다.
webpack.config.js
module.exports = {
externals: {
byLayer: {
layer: {
external1: "var 43",
},
},
},
};externalsType
string = 'var'
기본 외부 유형을 지정합니다. amd, umd, system 그리고 jsonp external은 output.libraryTarget이 동일한 값으로 설정되는 것에 의존합니다. 예. amd 라이브러리 내에서만 amd external을 사용할 수 있습니다.
지원 유형:
'amd''amd-require''assign'- same as'var''commonjs''commonjs-module''global''import'-import()를 사용하여 네이티브 EcmaScript 모듈을 로드합니다(비동기 모듈)'jsonp''module''import''module-import''node-commonjs''promise'-'var'과 동일하지만, 결과를 기다립니다(비동기 모듈)'self''system''script''this''umd''umd2''var''window'
webpack.config.js
module.exports = {
// ...
externalsType: "promise",
};externalsType.commonjs
외부속성의 기본 유형을 'commonjs'로 지정합니다. Webpack은 모듈에서 사용되는 외부속성에 대해 const X = require('...')와 같은 코드를 생성합니다.
Example
import fs from "fs-extra";webpack.config.js
module.exports = {
// ...
externalsType: "commonjs",
externals: {
"fs-extra": "fs-extra",
},
};이는 다음과 같이 생성됩니다.
const fs = require("fs-extra");출력 번들에 require()가 있다는 점을 유의하세요.
externalsType.global
외부 속성의 기본 유형을 'global'로 지정합니다. Webpack은 외부 속성을 globalObject의 전역 변수로 읽습니다.
Example
import jq from "jquery";
jq(".my-element").animate(/* ... */);webpack.config.js
module.exports = {
// ...
externalsType: "global",
externals: {
jquery: "$",
},
output: {
globalObject: "global",
},
};이는 다음과 같이 생성됩니다.
const jq = globalThis.$;
jq(".my-element").animate(/* ... */);externalsType.module
외부의 기본 유형을 'module'로 지정하세요. Webpack은 모듈에서 사용되는 외부 요소에 대해 import * as X from '...'와 같은 코드를 생성합니다.
우선 experiments.outputModule을 활성화해야 합니다. 그렇지 않으면 webpack에서 오류가 발생합니다.
Example
import jq from "jquery";
jq(".my-element").animate(/* ... */);webpack.config.js
module.exports = {
experiments: {
outputModule: true,
},
externalsType: "module",
externals: {
jquery: "jquery",
},
};이는 다음과 같이 생성됩니다.
import * as __WEBPACK_EXTERNAL_MODULE_jquery__ from "jquery";
const jq = __WEBPACK_EXTERNAL_MODULE_jquery__.default;
jq(".my-element").animate(/* ... */);출력 번들에 import 구문이 있다는 점을 유의하세요.
externalsType.import
5.94.0+외부의 기본 유형을 '가져오기'로 지정합니다. Webpack은 모듈에 사용되는 외부에 대해 '가져오기('...')'와 같은 코드를 생성합니다.
Example
async function foo() {
const jq = await import("jQuery");
jq(".my-element").animate(/* ... */);
}webpack.config.js
module.exports = {
externalsType: "import",
externals: {
jquery: "jquery",
},
};아래와 같이 생성합니다.
const __webpack_modules__ = {
jQuery: (module) => {
module.exports = import("jQuery");
},
};
// webpack 런타임...
async function foo() {
const jq = await Promise.resolve(/* import() */).then(
__webpack_require__.bind(__webpack_require__, "jQuery"),
);
jq(".my-element").animate(/* ... */);
}출력 번들에는 'import()' 구문이 있습니다.
externalsType.module-import
5.94.0+외부의 기본 유형을 module-import'`로 지정합니다. 이것은 [`'module'`](#externalstypemodule)과 [`'import'`](#externalstypeimport)를 결합합니다. Webpack은 자동으로 가져오기 구문의 유형을 감지하여 정적 가져오기의 경우 module'로, 동적 가져오기의 경우 ``import'로 설정합니다.
정적 가져오기가 있는 경우 먼저 experiments.outputModule을 활성화해야 합니다. 그렇지 않으면 webpack에서 오류가 발생합니다.
Example
import { attempt } from "lodash";
async function foo() {
const jq = await import("jQuery");
attempt(() => jq(".my-element").animate(/* ... */));
}webpack.config.js
module.exports = {
externalsType: "module-import",
externals: {
jquery: "jquery",
lodash: "lodash",
},
};아래와 같이 생성됩니다.
import * as __WEBPACK_EXTERNAL_MODULE_lodash__ from "lodash";
const lodash = __WEBPACK_EXTERNAL_MODULE_jquery__;
const __webpack_modules__ = {
jQuery: (module) => {
module.exports = import("jQuery");
},
};
// webpack 런타임...
async function foo() {
const jq = await Promise.resolve(/* import() */).then(
__webpack_require__.bind(__webpack_require__, "jQuery"),
);
(0, lodash.attempt)(() => jq(".my-element").animate(/* ... */));
}출력 번들에는 import 또는 import() 문이 포함됩니다.
모듈이 import 또는 import()를 통해 임포트되지 않으면 webpack은 "module" 외부 유형을 폴백으로 사용합니다. 다른 종류의 외부를 폴백으로 사용하려면 externals 옵션에서 함수로 지정할 수 있습니다. 예를 들어 보겠습니다.
module.exports = {
externalsType: "module-import",
externals: [
function ({ request, dependencyType }, callback) {
if (dependencyType === "commonjs") {
return callback(null, `node-commonjs ${request}`);
}
callback();
},
],
};externalsType.node-commonjs
외부의 기본 유형을 'node-commonjs'로 지정하세요. Webpack은 모듈에서 사용되는 외부 요소를 로드하기 위한 require 함수를 구성하기 위해 'module'에서 createRequire를 가져올 것입니다.
Example
import jq from "jquery";
jq(".my-element").animate(/* ... */);webpack.config.js
module.export = {
experiments: {
outputModule: true,
},
externalsType: "node-commonjs",
externals: {
jquery: "jquery",
},
};이는 다음과 같이 생성됩니다.
import { createRequire } from "node:module";
const jq = createRequire(import.meta.url)("jquery");
jq(".my-element").animate(/* ... */);출력 번들에 import 구문이 있다는 점을 유의하세요.
이것은 종속성이 Node.js 내장 모듈에 의존하거나 프로토타입을 보존하기 위해 CommonJS 스타일의 require 함수가 필요한 경우에 유용합니다. 이는 util.inherits와 같은 함수에 필요합니다. 자세한 내용은 이 이슈를 참고하세요.
다음은 프로토타입 구조에 의존하는 코드의 예시입니다.
function ChunkStream() {
Stream.call(this);
}
util.inherits(ChunkStream, Stream);node-commonjs를 사용하면 프로토타입 체인이 보존되는지 확인할 수 있습니다.
const { builtinModules } = require("node:module");
module.exports = {
experiments: { outputModule: true },
externalsType: "node-commonjs",
externals: ({ request }, callback) => {
if (request.startsWith("node:") || builtinModules.includes(request)) {
return callback(null, `node-commonjs ${request}`);
}
callback();
},
};이렇게 하면 다음과 같은 결과가 생성됩니다.
import { createRequire as __WEBPACK_EXTERNAL_createRequire } from "node:module";
const __webpack_modules__ = {
// ...
/***/ 2613: /***/ (module) => {
module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)(
"stream",
);
/***/
},
// ...
};이러한 설정은 프로토타입 구조를 그대로 유지하여 Node.js에 내장된 기능의 문제를 해결합니다.
externalsType.promise
외부 속성의 기본 유형을 'promise'로 지정합니다. Webpack은 외부 속성을 전역변수('var'와 유사함)로 읽고 await 합니다.
Example
import jq from "jquery";
jq(".my-element").animate(/* ... */);webpack.config.js
module.exports = {
// ...
externalsType: "promise",
externals: {
jquery: "$",
},
};이는 다음과 같이 생성됩니다.
const jq = await $;
jq(".my-element").animate(/* ... */);externalsType.self
외부 속성의 기본 유형을 'self'로 지정합니다. Webpack은 외부 속성을 self 객체의 전역 변수로 읽습니다.
Example
import jq from "jquery";
jq(".my-element").animate(/* ... */);webpack.config.js
module.exports = {
// ...
externalsType: "self",
externals: {
jquery: "$",
},
};이는 다음과 같이 생성됩니다.
const jq = globalThis.$;
jq(".my-element").animate(/* ... */);externalsType.script
외부의 기본 유형을 'script'로 지정하세요. Webpack은 HTML의 <script> 요소로 미리 정의된 전역 변수를 노출하는 스크립트로 외부를 로드합니다. <script> 태그는 스크립트가 로드된 후 제거됩니다.
Syntax
module.exports = {
externalsType: "script",
externals: {
packageName: [
"http://example.com/script.js",
"global",
"property",
"property",
], // 프로퍼티는 선택 사항입니다.
},
};프로퍼티를 지정하지 않을 경우 바로 가기 구문을 사용할 수도 있습니다.
module.exports = {
externalsType: "script",
externals: {
packageName: "global@http://example.com/script.js", // 여기엔 프로퍼티가 없습니다
},
};output.publicPath는 제공된 URL에 추가되지 않습니다.
Example
CDN에서 lodash를 로드해 보겠습니다.
webpack.config.js
module.exports = {
// ...
externalsType: "script",
externals: {
lodash: ["https://cdn.jsdelivr.net/npm/lodash@4.17.19/lodash.min.js", "_"],
},
};그런 다음 코드에서 사용합니다.
import _ from "lodash";
console.log(_.head([1, 2, 3]));위의 예제 코드를 위해 다음과 같이 프로퍼티를 지정해야 합니다.
module.exports = {
// ...
externalsType: "script",
externals: {
lodash: [
"https://cdn.jsdelivr.net/npm/lodash@4.17.19/lodash.min.js",
"_",
"head",
],
},
};로컬 변수 head와 전역 window._는 import lodash를 사용할 때 노출됩니다.
import head from "lodash";
console.log(head([1, 2, 3])); // 여기 로그는 1 입니다
console.log(globalThis._.head(["a", "b"])); // 여기 로그는 a 입니다externalsType.this
외부 속성의 기본 유형을 'this'로 지정합니다. Webpack은 외부 속성을 this 객체의 전역 변수로 읽습니다.
Example
import jq from "jquery";
jq(".my-element").animate(/* ... */);webpack.config.js
module.exports = {
// ...
externalsType: "this",
externals: {
jquery: "$",
},
};이는 다음과 같이 생성됩니다.
const jq = this.$;
jq(".my-element").animate(/* ... */);externalsType.var
외부 속성의 기본 유형을 'var'로 지정합니다. Webpack은 외부 속성을 전역 변수로 읽습니다.
Example
import jq from "jquery";
jq(".my-element").animate(/* ... */);webpack.config.js
module.exports = {
// ...
externalsType: "var",
externals: {
jquery: "$",
},
};이는 다음과 같이 생성됩니다.
const jq = $;
jq(".my-element").animate(/* ... */);externalsType.window
외부 속성의 기본 유형을 'window'로 지정합니다. Webpack은 외부 속성을 window 객체의 전역 변수로 읽습니다.
Example
import jq from "jquery";
jq(".my-element").animate(/* ... */);webpack.config.js
module.exports = {
// ...
externalsType: "window",
externals: {
jquery: "$",
},
};이는 다음과 같이 생성됩니다.
const jq = globalThis.$;
jq(".my-element").animate(/* ... */);externalsPresets
object
특정 대상에 대한 외부 프리셋 설정을 활성화합니다.
| Option | Description | Input Type |
|---|---|---|
electron | electron, ipc 또는 shell과 같은 main 및 preload 컨텍스트에서 공통 일렉트론 내장 모듈을 외부로 취급하고, 사용 시 require()를 통해 로드합니다. | boolean |
electronMain | app, ipc-main 또는 shell과 같은 같은 주 컨텍스트에서 일렉트론 내장 모듈을 외부로 취급하고, 사용 시 require()를 통해 로드합니다. | boolean |
electronPreload | web-frame, ipc-renderer 또는 shell과 같은 사전 로드 컨텍스트에서 일렉트론 내장 모듈을 외부로 취급하고, 사용 시 require()를 통해 로드합니다. | boolean |
electronRenderer | web-frame, ipc-renderer 또는 shell과 같은 렌더러 컨텍스트에서 일렉토론 내장 모듈을 외부로 취급하고, 사용 시 require()를 통해 로드합니다. | boolean |
node | fs, path 또는 vm과 같은 node.js 내장 모듈을 외부 모듈로 취급하고, 사용 시 require()를 통해 로드합니다. | boolean |
nwjs | NW.js 레거시 nw.gui 모듈을 외부 모듈로 취급하고, 사용 시 require()를 통해 로드합니다. | boolean |
web | http(s)://... 그리고 std:...에 대한 참조를 외부로 취급하고, 사용 시 import를 통해 로드합니다 (청크의 다른 코드보다 먼저 외부가 실행되므로 실행 순서가 변경됩니다). | boolean |
webAsync | http(s)://... 그리고 std:...에 대한 참조를 외부로 취급하고, 사용 시 async import()를 통해 로드합니다 (이 유형의 외부 모듈은 async 모듈이며, 실행에 다양한 영향을 미칩니다). | boolean |
node.js 관련 프리셋으로 ES 모듈을 출력하려는 경우, webpack은 기본externalsType을 node-commonjs로 설정하여, require()를 사용하는 대신 require 함수를 구성하기 위해 createRequire를 사용합니다.
Example
node 프리셋을 사용하면 내장 모듈을 번들로 묶지 않고 외부 모듈로 취급하고 사용할 때 require()를 통해 로드합니다.
webpack.config.js
module.exports = {
// ...
externalsPresets: {
node: true,
},
};
