Compilation Object
Compilation 객체에는 사용 가능한 많은 메소드와 훅이 있습니다. 이 페이지에서는, 사용 가능한 메소드와 프로퍼티를 나열합니다.
compilation object methods
아래 시그니처는 API 전반에 걸쳐 반복되는 두 가지 콜백 형태를 사용합니다:
type ModuleCallback = (
err?: WebpackError | null,
result?: Module | null,
) => void;
type ErrorCallback = (err?: WebpackError | null) => void;getStats
() => Stats
현재 컴파일에 대한 State 객체를 반환합니다.
addModule
(module: Module, callback: ModuleCallback) => void
현재 컴파일에 모듈을 추가합니다.
파라미터:
module- 추가할 모듈.callback- 모듈이 추가된 뒤의 콜백.
getModule
(module: Module) => Module
식별자를 통해 컴파일에서 모듈을 가져옵니다.
파라미터:
module- 가져올 모듈. 식별자는module.identifier()메소드를 사용한 컴파일을 통해 모듈에서 추출됩니다.
findModule
(identifier: string) => Module | undefined
식별자로 모듈 검색을 시도합니다. 모듈을 반환하거나, 일치하는 것이 없으면 undefined를 반환합니다.
파라미터:
identifier- 검색할 모듈의 식별자 문자열.
buildModule
(module: Module, callback: ModuleCallback) => void
주어진 모듈을 빌드합니다.
파라미터:
module- 빌드할 모듈.callback- 빌드가 완료되면callback(err, module)로 호출되는 함수.
processModuleDependencies
(module: Module, callback: ModuleCallback) => void
주어진 모듈 의존성을 처리합니다.
파라미터:
module- 의존성에 대해 처리할 모듈.callback- 모듈의 의존성이 처리되었을 때 호출되는 함수.
addEntry
(context: string, entry: Dependency, optionsOrName: string | EntryOptions, callback: ModuleCallback) => void
컴파일에 엔트리를 추가합니다.
파라미터:
context- 엔트리의 컨텍스트 경로.entry- 엔트리 의존성.name- 엔트리 이름.callback- addEntry가 완료될 때 호출되는 함수.
rebuildModule
(module: Module, callback: ModuleCallback) => void
모듈 재빌드를 트리거 합니다.
파라미터:
module- 재빌드 할 모듈.thisCallback- 모듈이 재빌드를 마쳤을 때 호출되는 함수.
finish
(callback: ErrorCallback) => void
컴파일을 완료하고 주어진 콜백을 호출합니다.
파라미터:
callback- 컴파일이 완료되면 호출되는 함수.
seal
(callback: ErrorCallback) => void
컴파일을 봉인합니다.
파라미터:
callback- 컴파일이 봉인되었을 때 호출되는 함수.
unseal
() => void
컴파일 봉인을 해제합니다.
reportDependencyErrorsAndWarnings
(module: Module, blocks: DependenciesBlock[]) => boolean
컴파일 오류 및 경고에 주어진 모듈의 오류 및 경고를 추가합니다.
파라미터:
module- 오류 및 경고를 보고할 모듈.blocks- 보고할 의존성 블록 집합.
addChunkInGroup
(groupOptions: string | ChunkGroupOptions, module?: Module, loc?: DependencyLocation, request?: string) => ChunkGroup
기존 청크 그룹에 모듈을 추가하거나 새 그룹을 만듭니다. chunkGroup을 반환합니다.
파라미터:
groupOptions- 청크 그룹에 대한 옵션.module- 청크 그룹을 참조하는 모듈.loc- 청크 그룹이 참조되는 위치(모듈 내부).request- 청크 그룹이 참조되는 요청.
addChunk
(name?: string | null) => Chunk
compilation.chunks에 새 청크를 만들고 추가합니다. 해당 chunk를 반환합니다.
파라미터:
name- 청크 이름.
addRuntimeModule
(chunk: Chunk, module: RuntimeModule, chunkGraph?: ChunkGraph) => void
청크에 런타임 모듈을 추가합니다. 컴파일에 모듈을 등록하고, 청크 그래프에서 청크에 연결하고 첨부하여, 모듈이 생성하는 코드가 해당 청크의 런타임의 일부가 됩니다. 플러그인은 보통 모듈이 구현하는 요구 사항에 대해 한 번씩 runtimeRequirementInTree에서 이를 호출합니다.
파라미터:
chunk- 런타임 모듈을 추가할 청크.module- 추가할RuntimeModule.chunkGraph- 연결할 청크 그래프; 기본값은 컴파일 자체의 청크 그래프.
addLazyRuntimeModule
(chunk: Chunk, load: () => Promise<any>, create: (loaded: any) => RuntimeModule, chunkGraph?: ChunkGraph) => void
구현이 필요할 때 로드되는 런타임 모듈을 큐에 넣습니다. 호출 중에는 어떤 콜백도 실행되지 않습니다: 런타임 요구 사항 패스가 끝나면 큐가 처리되고, 먼저 load가 대기되며, 그런 다음 create가 해석된 값에서 모듈을 빌드하고, 이는 addRuntimeModule이 추가하는 방식으로 추가됩니다.
파라미터:
chunk- 런타임 모듈을 추가할 청크.load- 런타임 모듈 구현을 해석합니다.create- 로드된 값에서RuntimeModule을 빌드합니다.chunkGraph- 연결할 청크 그래프; 기본값은 컴파일 자체의 청크 그래프.
assignDepth
(module: Module) => void
주어진 모듈과 그 의존성 블록에 재귀적으로 depth를 할당합니다.
파라미터:
module- depth를 할당할 모듈.
getDependencyReferencedExports
(dependency: Dependency, runtime: RuntimeSpec) => (string[] | ReferencedExport)[]
주어진 의존성이 참조하는 exports를 반환합니다.
파라미터:
dependency- 참조된 exports를 가져올 의존성.runtime- exports를 가져올 런타임.
removeReasonsOfDependencyBlock
(module: Module, block: DependenciesBlockLike) => void
모듈과 의존성 블록의 관계를 제거합니다.
파라미터:
module- 제거할 모듈 관계.block- 의존성 블록.
patchChunksAfterReasonRemoval
(module: Module, chunk: Chunk) => void
의존성 이유를 제거한 후 모듈 및 청크의 연결을 패치합니다. removeReasonsOfDependencyBlock에 의해 자동으로 호출됩니다.
파라미터:
module- 패치 할 모듈.chunk- 패치 할 청크.
removeChunkFromDependencies
(block: DependenciesBlock, chunk: Chunk) => void
의존성 이유를 제거한 후 의존성 블록 모듈 및 청크에서 주어진 청크를 제거합니다. removeReasonsOfDependencyBlock에 의해 자동으로 호출됩니다.
파라미터:
block-Chunk의 블록.chunk- 의존성에서 제거할 청크.
sortItemsWithChunkIds
() => void
summarizeDependencies
() => void
createHash
() => CodeGenerationJob[]
createModuleAssets
() => void
createChunkAssets
(callback: ErrorCallback) => void
getPath
(filename: string | TemplatePathFn, data?: PathData) => string
삽입된 경로를 반환합니다.
파라미터:
filename- 해시로 애셋 경로를 얻는 데 사용.data- data 객체.
getPathWithInfo
(filename: string | TemplatePathFn, data?: PathData) => { path: string, info: AssetInfo }
삽입된 경로 및 애셋 정보를 반환합니다.
파라미터:
filename- 해시로 애셋 경로를 얻는 데 사용.data- data 객체.
createChildCompiler
(name: string, outputOptions?: Partial<OutputNormalized>, plugins?: (WebpackPluginInstance | ((this: Compiler, compiler: Compiler) => void) | Falsy)[]) => Compiler
webpack 내에서 webpack의 다른 인스턴스를 실행할 수 있습니다. 그러나, 다른 설정과 구성이 적용된 하위 컴파일러로서 상위(또는 최상위 컴파일러)에서 모든 훅과 플러그인을 복사하고 하위 Compiler 인스턴스를 만듭니다. 생성된 Compiler를 반환합니다.
파라미터:
name- 하위Compiler의 이름.outputOptions- 출력 옵션 객체.plugins- 적용될 webpack 플러그인.
checkConstraints
() => void
emitAsset
(file: string, source: Source, assetInfo?: AssetInfo) => void
파라미터:
file- 애셋의 파일 이름source- 애셋의 소스assetInfo- 추가 애셋 정보, 생략 시{}
updateAsset
(file: string, newSourceOrFunction: Source | ((source: Source) => Source), assetInfoUpdateOrFunction?: AssetInfo | ((assetInfo?: AssetInfo) => AssetInfo | undefined)) => void
파라미터:
file- 애셋의 파일 이름newSourceOrFunction- 새 애셋 소스 또는 이전의 것을 새것으로 변환하는 함수assetInfoUpdateOrFunction- 새 애셋 정보 또는 이전의 것을 새것으로 변환하는 함수
deleteAsset
(file: string) => void
파라미터:
file- 애셋의 파일 이름
getAssets
() => Readonly<Asset>[]
현재 컴파일에서 모든 애셋의 배열을 반환합니다.
getAsset
(name: string) => Readonly<Asset> | undefined
파라미터:
name- 반환할 애셋의 이름
getCache
(name: string) => CacheFacade
주어진 이름으로 범위가 지정된 CacheFacade를 반환합니다. 플러그인이 빌드 간에 결과를 저장하고 지속 캐시에서 재사용하는 API입니다. compiler.getCache(name)이나 더 이상 사용되지 않는 compilation.cache 대신 이것을 사용하여, 캐시된 항목이 빌드 중인 컴파일에 속하도록 하세요.
파라미터:
name- 캐시를 식별하는 이름, 관례적으로 플러그인의 이름
compiler.hooks.compilation.tap("MyPlugin", (compilation) => {
const cache = compilation.getCache("MyPlugin");
compilation.hooks.processAssets.tapPromise("MyPlugin", async (assets) => {
for (const [name, source] of Object.entries(assets)) {
// the etag decides when an entry is stale: pass something derived
// from the inputs, here the source itself
const etag = cache.getLazyHashedEtag(source);
const cached = await cache.getPromise(name, etag);
if (cached !== undefined) {
compilation.updateAsset(name, cached);
continue;
}
const result = transform(source);
await cache.storePromise(name, etag, result);
compilation.updateAsset(name, result);
}
});
});CacheFacade가 제공하는 메서드:
| 메서드 | 설명 |
|---|---|
get(identifier, etag, callback) | 항목을 읽습니다. 유효한 것이 저장되지 않은 경우 콜백은 undefined를 받습니다. |
getPromise(identifier, etag) | get의 프로미스 형태입니다. |
store(identifier, etag, data, callback) | 항목을 씁니다. |
storePromise(identifier, etag, data) | store의 프로미스 형태입니다. |
provide(identifier, etag, computer, callback) | 항목을 읽거나, computer로 계산하고 결과를 저장합니다. |
getItemCache(identifier, etag) | 하나의 식별자와 etag에 바인딩된 ItemCacheFacade로, 식별자 없이 get / getPromise / store / storePromise / provide를 사용합니다. |
getChildCache(name) | name 아래에 항목이 네임스페이스된 중첩된 CacheFacade입니다. |
getLazyHashedEtag(obj) | Source와 같은 해시 가능한 객체에 대한 etag로, 실제로 필요할 때만 계산됩니다. |
mergeEtags(a, b) | 항목이 둘 이상의 입력에 의존할 때, 두 etag를 나타내는 하나의 etag입니다. |
isEnabled() | 캐싱이 전혀 활성화되어 있는지 여부입니다. |
Module and chunk graphs
5.0.0+webpack 5는 모듈과 청크 간의 관계를 Module과 Chunk 객체 자체에서 꺼내어 컴파일이 보유하는 두 그래프로 옮겼습니다:
compilation.moduleGraph— 모듈이 서로 관계 맺는 방식: 어떤 모듈이 어떤 모듈을 요청했는지, 의존성이 무엇을 참조하는지, 어떤 exports가 사용되는지.compilation.chunkGraph— 모듈이 청크와 관계 맺는 방식: 어떤 청크가 모듈을 포함하는지, 모듈의 id와 해시, 어떤 모듈이 청크의 엔트리 모듈인지.
그 이유는 하나의 모듈이 이제 여러 그래프에 참여할 수 있기 때문입니다 (한 번 빌드된 모듈이 둘 이상의 런타임에 나타날 수 있음), 따라서 "이 모듈의 id"와 같은 값은 그래프와 함께할 때만 의미가 있습니다.
compilation.hooks.optimizeChunks.tap("MyPlugin", (chunks) => {
const { chunkGraph, moduleGraph } = compilation;
for (const chunk of chunks) {
for (const module of chunkGraph.getChunkModules(chunk)) {
const id = chunkGraph.getModuleId(module);
const issuer = moduleGraph.getIssuer(module);
// ...
}
}
});이전 멤버에 접근하는 것은 여전히 작동하지만, DEP_WEBPACK_* 코드를 명시하는 지원 중단 경고를 로그에 남깁니다. 다음은 대체 방법입니다:
| 지원 중단 | 대체 방법 |
|---|---|
chunk.entryModule | chunkGraph.getChunkEntryModulesIterable(chunk) |
chunk.hasEntryModule() | chunkGraph.getNumberOfEntryModules(chunk) > 0 |
chunk.getModules() | chunkGraph.getChunkModules(chunk) |
chunk.modulesIterable | chunkGraph.getChunkModulesIterable(chunk) |
chunk.getNumberOfModules() | chunkGraph.getNumberOfChunkModules(chunk) |
chunk.containsModule(module) | chunkGraph.isModuleInChunk(module, chunk) |
chunk.addModule(module) | chunkGraph.connectChunkAndModule(chunk, module) |
chunk.removeModule(module) | chunkGraph.disconnectChunkAndModule(chunk, module) |
chunk.moveModule(module, other) | chunkGraph.disconnectChunkAndModule(chunk, module) then connectChunkAndModule |
chunk.remove() | chunkGraph.disconnectChunk(chunk) and chunk.disconnectFromGroups() |
chunk.isEmpty() | chunkGraph.getNumberOfChunkModules(chunk) === 0 |
chunk.integrate(other) | chunkGraph.integrateChunks(chunk, other) |
chunk.canBeIntegrated(other) | chunkGraph.canChunksBeIntegrated(chunk, other) |
chunk.integratedSize(other, options) | chunkGraph.getIntegratedChunksSize(chunk, other, options) |
chunk.modulesSize() | chunkGraph.getChunkModulesSize(chunk) |
chunk.size(options) | chunkGraph.getChunkSize(chunk, options) |
chunk.compareTo(other) | chunkGraph.compareChunks(chunk, other) |
chunk.hasModuleInGraph(filter, filter2) | chunkGraph.hasModuleInGraph(chunk, filter, filter2) |
module.id | chunkGraph.getModuleId(module) |
module.hash | chunkGraph.getModuleHash(module, runtime) |
module.renderedHash | chunkGraph.getRenderedModuleHash(module, runtime) |
module.getChunks() | chunkGraph.getModuleChunks(module) |
module.getNumberOfChunks() | chunkGraph.getNumberOfModuleChunks(module) |
module.isInChunk(chunk) | chunkGraph.isModuleInChunk(module, chunk) |
module.addChunk(chunk) | chunkGraph.connectChunkAndModule(chunk, module) |
module.removeChunk(chunk) | chunkGraph.disconnectChunkAndModule(chunk, module) |
module.isEntryModule() | chunkGraph.isEntryModule(module) |
module.index | moduleGraph.getPreOrderIndex(module) |
module.index2 | moduleGraph.getPostOrderIndex(module) |
module.depth | moduleGraph.getDepth(module) |
module.issuer | moduleGraph.getIssuer(module) |
module.usedExports | moduleGraph.getUsedExports(module, runtime) |
module.optimizationBailout | moduleGraph.getOptimizationBailout(module) |
module.profile | moduleGraph.getProfile(module) |
module.optional | module.isOptional(moduleGraph) |
dependency.originModule | moduleGraph.getParentModule(dependency) |