CC 4.0 ライセンス
このセクションの内容は、以下のリンクの内容から派生しており、CC BY 4.0ライセンスに従います。
特に明記されていない限り、以下の内容は、元の内容に基づいて修正および削除が行われた結果と見なすことができます。
コンパイル
このページでは、コンパイルオブジェクトで利用可能なメソッドとプロパティをリストアップします。
注意
Rspackでは、実際のコンパイルオブジェクトはRust側で実行され、JavaScriptコンパイルオブジェクトはRustコンパイルオブジェクトと通信するために使用されるプロキシオブジェクトにすぎません。
したがって、一部の複雑なデータ構造とメソッドはJavaScriptコンパイルオブジェクトではサポートされません。データは読み取り専用であり、構造はwebpackと異なる場合があります。
コンパイルメソッド
emitAsset
新しいアセットを発行します。アセットがすでに存在する場合はエラーをスローします。
emitAsset(
filename: string, // filename of the new asset
source: Source, // content of the new asset
info?: AssetInfo // asset info of the new asset
): void;
次のコードでは、asset-name.js
という名前の新しいアセットが追加され、圧縮されません。
compiler.hooks.thisCompilation.tap('MyPlugin', compilation => {
const { RawSource } = compiler.webpack.sources;
compilation.hooks.processAssets.tap('MyPlugin', () => {
const buffer = Buffer.from(
'i am content of emit asset, do not minimize me',
);
const source = new RawSource(buffer, false);
compilation.emitAsset('asset-name.js', source, {
minimized: true,
});
});
});
updateAsset
既存のアセットを更新します。アセットが存在しない場合はエラーをスローします。
updateAsset(
filename: string, // filename of the updating asset
source: Source | ((source: Source) => Source), // the new content or a function returns the new content
info?: // the new info or a function returns the new info
| AssetInfo
| ((assetInfo: AssetInfo) => AssetInfo)
): void;
次のコードでは、main.js
の内容が置き換えられ、最小化されません。
compiler.hooks.thisCompilation.tap('MyPlugin', compilation => {
const { RawSource } = compiler.webpack.sources;
compilation.hooks.processAssets.tap('MyPlugin', () => {
const updatedSource = new RawSource(
`module.exports = "This is the updated"`,
);
compilation.updateAsset('main.js', updatedSource, {
minimized: true,
});
});
});
renameAsset
既存のアセットの名前を変更します。
renameAsset(
filename: string, // filename of the renaming asset
newFilename: string // new filename
): void;
次のコードでは、main.js
という名前のアセットの名前がmy-asset-name.js
に変更されます。
compiler.hooks.thisCompilation.tap('MyPlugin', compilation => {
compilation.hooks.processAssets.tap('MyPlugin', () => {
compilation.renameAsset('main.js', 'my-asset-name.js');
});
});
deleteAsset
既存のアセットを削除します。
deleteAsset(
filename: string // filename of the deleting asset
): void;
次のコードでは、no-need.js
という名前のアセットが削除されます。
compiler.hooks.thisCompilation.tap('MyPlugin', compilation => {
compilation.hooks.processAssets.tap('MyPlugin', () => {
compilation.deleteAsset('no-need.js');
});
});
getAssets
アセットオブジェクトのリストを取得します。
getAssets(): ReadonlyArray<{
filename: string;
source: Source;
info: AssetInfo;
}>;
次のコードでは、すべてのアセットの合計サイズが出力されます。
compiler.hooks.compilation.tap('MyPlugin', compilation => {
compilation.hooks.processAssets.tap('MyPlugin', () => {
const assets = compilation.getAssets();
const totalSize = assets.reduce(
(total, asset) => total + asset.source.size(),
0,
);
console.log(`total size: ${totalSize}`);
});
});
getAsset
指定された名前のアセットオブジェクトを取得します。
getAsset(
filename: string // filename of the getting asset
): Readonly<{
filename: string;
source: Source;
info: AssetInfo;
}> | void;
次のコードでは、main.js
という名前のアセットのサイズが出力されます。
compiler.hooks.compilation.tap('MyPlugin', compilation => {
compilation.hooks.processAssets.tap('MyPlugin', () => {
const assetSize = compilation.getAsset('main.js')?.source.size();
console.log(`main size: ${assetSize}`);
});
});
getPath
ファイル名テンプレートに基づいてパス文字列を生成します。テンプレートのルールについては、テンプレート文字列を参照してください。
getPath(
filename: Filename, // filename template
data: PathData = {} // generating path data
): string;
次のコードでは、テンプレート内のプレースホルダーが置き換えられてパスが生成されます。
const path = compilation.getPath('[contenthash]-[fullhash].js', {
contentHash: 'some1',
hash: 'some2',
});
console.log(path); // "some1-some2.js"
getPathWithInfo
ファイル名テンプレートに基づいてパス文字列とアセット情報を生成します。詳細については、テンプレート文字列を参照してください。
getPathWithInfo(
filename: Filename, // filename template
data: PathData = {} // generating path data
): {
path: string;
info: AssetInfo;
};
次のコードでは、テンプレート内のプレースホルダーが置き換えられてパスとアセット情報が生成されます。
const { path, info } = compilation.getPathWithInfo(
'[contenthash]-[fullhash].js',
{
contentHash: 'some1',
hash: 'some2',
},
);
console.log(path); // "some1-some2.js"
console.log(info);
/* Object {
immutable: true,
minimized: false,
fullhash: [ 'some2' ],
chunkhash: [],
contenthash: [ 'some1' ],
development: false,
hotModuleReplacement: false,
related: {},
extras: {}
} */
getStats
現在のコンパイルの統計オブジェクトを取得します。
次のコードでは、モジュールの総数が出力されます。
compiler.hooks.emit.tapAsync('MyPlugin', compilation => {
const modules = compilation.getStats().toJson({ modules: true }).modules;
console.log(`Total modules: ${modules.length}`);
});
createChildCompiler
Rspack内部で別のRspackインスタンスを実行できます。ただし、異なる設定と構成が適用された子として実行されます。親(またはトップレベルのコンパイラ)からすべてのフックとプラグインをコピーし、子Compiler
インスタンスを作成します。作成されたCompiler
を返します。
createChildCompiler(
name: string, // name for the child `Compiler`
outputOptions: OutputNormalized, // Output options object
plugins: RspackPluginInstance[] // Plugins that will be applied
): Compiler;
次のコードでは、child-entry.js
をエントリとして、dist/child
に出力する子コンパイラが起動されます。
compiler.hooks.make.tap('MyPlugin', compilation => {
const childCompiler = compilation.createChildCompiler(
'ChildCompiler',
{
path: 'dist/child',
},
[new compiler.webpack.EntryPlugin(compiler.context, './child-entry.js')],
);
childCompiler.compile((err, childCompilation) => {});
});
addRuntimeModule
コンパイルにカスタムランタイムモジュールを追加します。
addRuntimeModule(
c: Chunk, // the runtime chunk which to add the runtime module
m: RuntimeModule, // the runtime module instance to add
): void;
次のコードでは、__webpack_require__.mock
を"main"
チャンクに定義するランタイムモジュールが追加されます。
rspack.config.js
module.exports = {
entry: './index.js',
plugins: [
{
apply(compiler) {
const { RuntimeModule } = compiler.webpack;
class CustomRuntimeModule extends RuntimeModule {
constructor() {
super('custom');
}
generate() {
const compilation = this.compilation;
return `
__webpack_require__.mock = function() {
// ...
};
`;
}
}
compiler.hooks.thisCompilation.tap('CustomPlugin', compilation => {
compilation.hooks.runtimeRequirementInTree
.for(RuntimeGlobals.ensureChunkHandlers)
.tap('CustomPlugin', (chunk, set) => {
if (chunk.name === 'main') {
compilation.addRuntimeModule(chunk, new CustomRuntimeModule());
}
});
});
},
},
],
};
カスタムランタイムモジュールクラスを実装する場合、次のメソッド/プロパティをオーバーライドしてランタイムモジュールの動作を制御できます。
- コンストラクターで
name
およびstage
パラメーターを渡して、モジュール名と挿入ステージを指定します。
generate()
メソッドをオーバーライドして、モジュールの生成されたコードを制御します。
shouldIsolate()
メソッドをオーバーライドして、モジュールがIIFEでラップされるかどうかを制御します。
attach()
メソッドをオーバーライドして、モジュールが追加されたときの動作を修正します。
fullHash
またはdependentHash
プロパティを変更して、モジュールをキャッシュできるかどうかを制御します。
rebuildModule
モジュールの再構築をトリガーします。
rebuildModule(
m: Module, // module to be rebuilt
f: (err: Error, m: Module) => void // function to be invoked when the module finishes rebuilding
): void;
次のコードでは、a.js
で終わるモジュールが再構築されます。
compiler.hooks.compilation.tap('MyPlugin', compilation => {
compilation.hooks.finishModules.tapPromise('MyPlugin', async modules => {
const oldModule = Array.from(modules).find(item =>
item.resource.endsWith('a.js'),
);
compilation.rebuildModule(oldModule, (err, m) => {
console.log(`Rebuilt ${m.identifier()}.`);
});
});
});
getLogger
指定された名前のログ出力ユーティリティオブジェクトを取得します。これは、プラグインで統合された形式でログを出力するために使用できます。
getLogger(name: string | (() => string)): Logger;
次のコードでは、processAssets
でアセットがデバッグログに出力されます。
compiler.hooks.compilation.tap('MyPlugin', compilation => {
const logger = compilation.getLogger('MyPlugin');
compilation.hooks.processAssets.tap('MyPlugin', () => {
for (const asset of compilation.getAssets()) {
logger.debug(`asset name: ${asset.name}`);
logger.debug(`asset info: ${asset.info}`);
}
});
});
getCache
指定された名前のキャッシュオブジェクトを取得します。これは、プラグインが複数のコンパイル中にデータを共有するために使用できます。
getCache(name: string): CacheFacade;
コンパイルプロパティ
options
タイプ: RspackOptionsNormalized
このコンパイルで使用される正規化されたオプション。詳細については、Rspackの設定を参照してください。
compiler
タイプ: Compiler
現在のコンパイラオブジェクト。
hooks
コンパイルフック。
hash/fullhash
タイプ: Readonly<string | null>
このコンパイルのハッシュ。
assets
タイプ: Record<string, Source>
アセットファイル名とコンテンツソースのマッピング。
chunkGroups
タイプ: ReadonlyArray<ChunkGroup>
チャンクグループオブジェクトのリスト。構造は次のとおりです。
entrypoints
タイプ: ReadonlyMap<string, Entrypoint>
名前からエントリポイントへのマッピング。これは特別なチャンクグループであり、ランタイムチャンクが含まれています。
namedChunkGroups
タイプ: ReadonlyMap<string, Readonly<ChunkGroup>>
名前からチャンクグループへのマッピング。
modules
型: ReadonlySet<Module>
すべてのモジュールのリスト。構造は以下の通りです。
builtModules
型: ReadonlySet<Module>
キャッシュされなかったビルド済みモジュールのリスト。構造は以下の通りです。
chunks
型: ReadonlySet<Chunk>
すべてのチャンクのリスト。構造は以下の通りです。
namedChunks
型: ReadonlyMap<string, Readonly<Chunk>>
名前からチャンクへのマッピング。
fileDependencies
型: CompilationDependencies
このコンパイルが依存するファイルのリスト。
contextDependencies
型: CompilationDependencies
このコンパイルが依存するディレクトリのリスト。
missingDependencies
型: CompilationDependencies
このコンパイルが依存する存在しないファイルのリスト。
buildDependencies
型: CompilationDependencies
このコンパイルが依存するビルド依存関係のリスト。
errors
型: RspackError[]
このコンパイル中に発生したエラーのリスト。構造は以下の通りです。
warnings
型: RspackError[]
このコンパイル中に発生した警告のリスト。