示例工程 16-mini-bundler
16-mini-bundler/01-mini-bundler/main.js
点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。
// main.js —— 在浏览器里加载并求值打包产物(测试用同一函数)
export function evaluateBundle(source, globalName = '__miniBundle') {
const factory = new Function(`${source}\nreturn globalThis.${globalName};`);
return factory();
}
export async function run(log = console.log) {
if (typeof fetch !== 'function') {
throw new Error('本示例需要浏览器环境:请通过 index.html 打开');
}
const res = await fetch('./dist/bundle.js');
if (!res.ok) throw new Error(`加载 bundle 失败:HTTP ${res.status}`);
const api = evaluateBundle(await res.text());
const result = api.run();
log(`banner:${result.banner}`);
log(`共享 utils 引用:${result.sameUtils}`);
log(`循环依赖视图:${JSON.stringify(result.cycle)}`);
log('产物由 scripts/mini-bundler/build.mjs 生成,index.html 也可以直接用 <script> 引入。');
return result;
}