Parcel 如何自动收集所有构建入的依赖许可证并生成 THIRD_PARTY_NOTICES.txt?请指出 reporter 插件。
解读
面试官想确认三件事:
- 你是否知道 Parcel 的“依赖图”里已经完整保存了 npm 包的元数据(含 license 字段);
- 你是否理解 Parcel 的插件体系里“reporter”是唯一能在构建结束后拿到完整统计信息的钩子;
- 你是否能给出一条国内可落地的技术路径(不依赖国外 SaaS、不手写爬虫),让 CI 一键生成合规的 THIRD_PARTY_NOTICES.txt,满足国内大厂法务/审计的刚性需求。
知识点
- Parcel 的依赖图(AssetGraph)在 transform 阶段会把每个 npm 包 package.json 中的 license、repository、author 字段缓存到内存;
- Reporter 插件接口:@parcel/plugin 的 reporter 模块会在 buildSuccess、buildFailure 事件里收到 BundleGraph 与 RequestGraph,可以遍历 graph.getBundleGraph().getNodeByContentKey() 拿到所有依赖;
- 许可证合规的国内落地要点:
- 必须同时收集“直接依赖”与“间接依赖”;
- 必须处理 SPDX 表达式(如 MIT OR Apache-2.0)并给出原文链接;
- 必须去重并按包名排序,方便法务二次审计;
- 必须支持私有包白名单(国内常见场景);
- 官方社区已有 @parcel/reporter-license-list,但默认只输出 JSON,需要二次封装成 txt;
- 生成时机:放在 CI 的最后一步,产物上传前,通过 npx parcel build --reporter ./license-reporter 触发。
答案
步骤一:安装官方 reporter 并扩展 npm i -D @parcel/reporter-license-list
步骤二:在项目根新建 parcel-license-reporter.js const { Reporter } = require('@parcel/plugin'); const fs = require('fs'); const path = require('path');
module.exports = new Reporter({ async report({ event, options }) { if (event.type !== 'buildSuccess') return;
const licenseMap = new Map();
const bundleGraph = event.bundleGraph;
bundleGraph.traverseBundles(bundle => {
bundle.getEntryAssets().forEach(asset => {
const pkg = asset.meta.pkg; // 官方已注入 package.json 元数据
if (!pkg || !pkg.name) return;
const key = `${pkg.name}@${pkg.version}`;
if (licenseMap.has(key)) return;
licenseMap.set(key, {
name: pkg.name,
version: pkg.version,
license: pkg.license || 'UNKNOWN',
repository: pkg.repository?.url || pkg.repository || '',
licenseFile: pkg.licenseFile || ''
});
});
});
// 按包名排序并去重
const notices = Array.from(licenseMap.values())
.sort((a, b) => a.name.localeCompare(b.name))
.map(item => {
return `Package: ${item.name}@${item.version}
License: {item.repository} ${item.licenseFile ? 'LicenseFile: ' + item.licenseFile : ''} `; }) .join('\n');
fs.writeFileSync(
path.join(options.projectRoot, 'THIRD_PARTY_NOTICES.txt'),
notices,
'utf8'
);
console.log('✅ THIRD_PARTY_NOTICES.txt 已生成,共 %d 个依赖', licenseMap.size);
} });
步骤三:在 .parcelrc 中注册 { "extends": "@parcel/config-default", "reporters": ["...", "./parcel-license-reporter.js"] }
步骤四:CI 脚本 parcel build && ls -lh THIRD_PARTY_NOTICES.txt
至此,Parcel 会在每次构建结束后自动扫描依赖图,把许可证信息汇总成国内法务可直接审阅的 THIRD_PARTY_NOTICES.txt,无需任何额外 SaaS 或手工维护。
拓展思考
- 如果企业要求把许可证原文一并打包,可在 reporter 里读取每个包的 LICENSE 文件内容(通过 asset.fs.readFileSync 读取 node_modules 下的 LICENSE*),体积会增大,需二次压缩;
- 对于“双许可证”场景(如 GPL-3.0 OR Commercial),可在 reporter 里加白名单配置,自动发企业微信/飞书告警,提示法务人工确认;
- 在微前端仓库里,主应用与子应用分别构建,需把 reporter 抽成独立 npm 包,统一在 monorepo 根执行一次即可,避免重复;
- 国内私有 npm 源(如 Verdaccio)可能缺失 license 字段,可在 CI 前置步骤做 npm audit --json 二次补全,保证数据完整性;
- 若未来 Parcel 升级至 Rust 核心,官方可能把 license 数据下沉到 Rust 侧,reporter 写法不变,但遍历 API 会改为异步迭代器,需提前封装适配层,保证平滑升级。