示例工程 16-mini-bundler
16-mini-bundler/02-request-waterfall/main.js
点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。
// main.js —— 不打包时的请求瀑布:N 个模块 = N 次往返
export function compareRequests({ modules, rttMs }) {
const unbundled = modules * rttMs;
const bundled = rttMs;
return {
modules,
unbundledMs: unbundled,
bundledMs: bundled,
savedMs: unbundled - bundled,
requests: { unbundled: modules, bundled: 1 },
};
}
export function run(log = console.log) {
const rows = [
['6 个模块、RTT 50ms', compareRequests({ modules: 6, rttMs: 50 })],
['20 个模块、RTT 50ms', compareRequests({ modules: 20, rttMs: 50 })],
['100 个模块、RTT 20ms', compareRequests({ modules: 100, rttMs: 20 })],
];
log('场景 => 结果');
for (const [label, value] of rows) {
log(
`${label} => 请求 ${value.requests.unbundled} 次 / ${value.unbundledMs}ms;` +
`打包后 1 次 / ${value.bundledMs}ms;节省 ${value.savedMs}ms`,
);
}
log('-'.repeat(50));
log('要点:HTTP 往返是固定成本,模块越多,串行瀑布越贵;打包用一次请求换掉 N 次。');
return rows;
}