示例工程 17-tree-shaking-splitting-hmr

17-tree-shaking-splitting-hmr/03-code-splitting/main.js

javascript · 1.7 KB

运行:17 · code splitting

点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。

// main.js —— 按「静态依赖」与「动态 import()」划分 chunk
// 入口静态可达的模块进 entry;动态边界之后、且不在 entry 的模块各自成 chunk。
 
export function staticClosure(start, modules) {
  const seen = new Set();
  const stack = [start];
  while (stack.length) {
    const id = stack.pop();
    if (seen.has(id) || !Object.hasOwn(modules, id)) continue;
    seen.add(id);
    for (const dep of modules[id].deps || []) stack.push(dep);
  }
  return seen;
}
 
export function splitChunks(entry, modules) {
  const entrySet = staticClosure(entry, modules);
  const chunks = { entry: [...entrySet] };
 
  for (const [id, mod] of Object.entries(modules)) {
    for (const dynamic of mod.dynamic || []) {
      const lazy = [...staticClosure(dynamic, modules)].filter((x) => !entrySet.has(x));
      if (lazy.length) chunks[`chunk:${dynamic}`] = lazy;
    }
  }
  return chunks;
}
 
export function chunkOf(id, chunks) {
  for (const [name, ids] of Object.entries(chunks)) {
    if (ids.includes(id)) return name;
  }
  return null;
}
 
export const FIXTURES = {
  './main.js': { deps: ['./util.js'], dynamic: ['./lazy.js'] },
  './util.js': { deps: ['./shared.js'] },
  './shared.js': { deps: [] },
  './lazy.js': { deps: ['./lazy-util.js', './shared.js'] },
  './lazy-util.js': { deps: [] },
};
 
export function run(log = console.log) {
  const chunks = splitChunks('./main.js', FIXTURES);
  log('chunk 划分:');
  for (const [name, ids] of Object.entries(chunks)) log(`  ${name}: ${ids.join(', ')}`);
  log('shared 模块被提升到 entry:两个 chunk 都用到它,只应加载一次。');
  log('lazy 的加载由 import() 触发,不会进入首屏产物。');
  return { chunks, sharedChunk: chunkOf('./shared.js', chunks) };
}