本篇是 Rspack 源码解析系列第三十六篇。BannerPlugin 是 webpack 生态里常见的小插件,作用是在每个 chunk 文件的头部(或尾部)加一段注释,常用于版权声明或构建信息。本文进入
crates/rspack_plugin_banner,看这个「小插件」如何利用process_assetsHook、match_object条件和Filename占位符系统完成注入。
前言:小插件里的三个通用模式
BannerPlugin 代码不到 200 行,但它浓缩了 Rspack 插件开发的三个通用模式:
text
1. process_assets Hook:在产物生成后、写盘前修改 asset 内容
2. match_object 条件:test / include / exclude 过滤文件
3. Filename 占位符:让 banner 内容支持 [hash]、[chunkhash] 等模板
理解了这三个模式,就能举一反三写出大多数「改产物」的插件。
源码入口:BannerPluginOptions
crates/rspack_plugin_banner/src/lib.rs 顶部定义选项:
rust
#[derive(Debug)]
pub struct BannerPluginOptions {
pub banner: BannerContent,
pub entry_only: Option<bool>,
pub footer: Option<bool>,
pub raw: Option<bool>,
pub test: Option<AssetConditions>,
pub include: Option<AssetConditions>,
pub exclude: Option<AssetConditions>,
pub stage: Option<i32>,
}
banner 是内容,支持两种形态:
rust
pub enum BannerContent {
String(String), // 静态字符串
Fn(BannerContentFn), // 动态函数
}
BannerContentFn 接收一个上下文,返回 Future:
rust
pub type BannerContentFn =
Box<dyn for<'a> Fn(BannerContentFnCtx<'a>) -> BoxFuture<'a, Result<String>> + Sync + Send>;
上下文里有 hash、chunk、filename、compilation,让函数能根据当前产物动态生成 banner。
wrap_comment:注释包装逻辑
wrap_comment 把字符串包成块注释:
rust
static TRIALING_WHITESPACE: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"\s+\n").expect("invalid regexp"));
fn wrap_comment(str: &str) -> String {
if !str.contains('\n') {
return to_comment(str);
}
let result = str
.cow_replace("*/", "* /") // 防止破坏注释闭合
.split('\n')
.collect::<Vec<_>>()
.join("\n * ");
let result = TRIALING_WHITESPACE.replace_all(&result, "\n");
let result = result.trim_end();
format!("/*!\n * {result}\n */")
}
两个细节:
cow_replace("*/", "* /"):防止用户内容里的*/提前闭合注释;- 多行内容自动加
*前缀,保持注释对齐。
BannerPlugin::wrap_comment 决定是否包装:
rust
fn wrap_comment(&self, value: &str) -> String {
if let Some(true) = self.config.raw {
value.to_owned() // raw 模式:不包注释,直接原样
} else {
wrap_comment(value)
}
}
update_source:footer 决定前后
update_source 用 ConcatSource 拼接:
rust
fn update_source(&self, comment: String, old: BoxSource, footer: Option<bool>) -> BoxSource {
let old_source = old.clone();
if let Some(footer) = footer && footer {
ConcatSource::new([
old_source,
RawStringSource::from_static("\n").boxed(),
RawStringSource::from(comment).boxed(),
]).boxed()
} else {
ConcatSource::new([
RawStringSource::from(comment).boxed(),
RawStringSource::from_static("\n").boxed(),
old_source,
]).boxed()
}
}
footer=true 时注释放末尾,否则放开头。ConcatSource 惰性拼接多个 source,避免整段拷贝。
process_assets Hook:核心逻辑
process_assets 是主流程:
rust
#[plugin_hook(CompilationProcessAssets for BannerPlugin, stage = self.config.stage.unwrap_or(Compilation::PROCESS_ASSETS_STAGE_ADDITIONS))]
async fn process_assets(&self, compilation: &mut Compilation) -> Result<()> {
let logger = compilation.get_logger("rspack.BannerPlugin");
let start = logger.time("add banner");
let mut updates = vec![];
let condition_object = AssetConditionsObject {
test: self.config.test.as_ref(),
include: self.config.include.as_ref(),
exclude: self.config.exclude.as_ref(),
};
// ...
}
注意 stage 默认是 PROCESS_ASSETS_STAGE_ADDITIONS,即「附加内容」阶段------这也对应第 34 篇讲过的 stage 排序机制。
遍历 chunk 与过滤
遍历所有 chunk,先处理 entry_only:
rust
for chunk in compilation.build_chunk_graph_artifact.chunk_by_ukey.values() {
let can_be_initial = chunk.can_be_initial(&compilation.build_chunk_graph_artifact.chunk_group_by_ukey);
if let Some(entry_only) = self.config.entry_only
&& entry_only
&& !can_be_initial {
continue; // entry_only 且不是初始 chunk,跳过
}
for file in chunk.files() {
let is_match = match_object(&condition_object, file);
if !is_match { continue; }
// ...
}
}
match_object 是 Rspack 的通用条件匹配工具,把 test/include/exclude 三个条件组合成最终布尔结果:先看 include,再看 exclude,最后看 test。
生成 banner 内容(含占位符)
拿到匹配的文件后,先取 hash,再根据 banner 类型生成:
rust
let hash = compilation.hash.as_ref()
.expect("should have compilation.hash in process_assets hook")
.encoded().to_owned();
let banner = match &self.config.banner {
BannerContent::String(content) => self.wrap_comment(content),
BannerContent::Fn(func) => {
let res = func(BannerContentFnCtx {
hash: &hash, chunk, filename: file, compilation,
}).await?;
self.wrap_comment(&res)
}
};
然后是关键一步------get_path 处理占位符:
rust
let comment = compilation.get_path(
&Filename::from(banner),
PathData::default()
.chunk_hash_optional(chunk.rendered_hash(&compilation.chunk_hashes_artifact, compilation.options.output.hash_digest_length))
.chunk_id_optional(chunk.id().map(|id| id.as_str()))
.chunk_name_optional(chunk.name_for_filename_template())
.hash(&hash)
.filename(file),
).await?;
即使 banner 是静态字符串,也走 get_path,因为用户可能在 banner 里写 [hash]、[chunkhash]、[name]、[id]。PathData 填充了这些占位符需要的值。
收集后统一更新
遍历完成后,统一 update_asset:
rust
for (file, comment) in updates {
let _res = compilation.update_asset(file.as_str(), |old, info| {
let new = self.update_source(comment, old, self.config.footer);
Ok((new, info))
});
}
先收集 updates,再统一更新,避免边遍历边修改 compilation.assets() 导致的借用冲突。
apply:注册 Hook
rust
impl Plugin for BannerPlugin {
fn name(&self) -> &'static str { "rspack.BannerPlugin" }
fn apply(&self, ctx: &mut rspack_core::ApplyContext<'_>) -> Result<()> {
ctx.compilation_hooks.process_assets.tap(process_assets::new(self));
Ok(())
}
}
process_assets::new(self) 正是第 34 篇讲的 #[plugin_hook] 生成的 tap 结构体构造。
Rust 角度:占位符复用 Filename 系统
BannerPlugin 的占位符处理没有自己造轮子,而是复用了 Filename + PathData 这套输出文件名的模板系统。这体现了 Rspack 内部的一致抽象:任何需要模板字符串的地方,都走同一个 get_path 机制,占位符语义全项目统一。
get_path 是异步的,因为模板可能触发异步计算(例如 contenthash)。这也是 process_assets 必须是 async 的原因之一。
这一篇应该带走什么
- BannerPlugin 在
process_assets(ADDITIONS 阶段)修改 asset; match_object统一处理 test/include/exclude 过滤;wrap_comment防止*/破坏注释、多行对齐;get_path+PathData让 banner 支持[hash]/[chunkhash]占位符;- 先收集 updates 再统一
update_asset,避免借用冲突。
写在最后
BannerPlugin 的 get_path 用到了 chunk.rendered_hash------但这个 hash 在 process_assets 阶段还是「占位 hash」。真正的内容 hash 要等产物内容确定后才能算。下一篇进入 rspack_plugin_real_content_hash,看它如何用 Aho-Corasick 多模式匹配,把占位 hash 换成真实的 contenthash。