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
The 编译钩子.
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[]
此编译期间发出的警告列表。