示例工程 17-tree-shaking-splitting-hmr
17-tree-shaking-splitting-hmr/02-mini-tree-shaker/main.test.mjs
点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { FIXTURES, run, treeShake } from './main.js';
const result = treeShake('./main.js', FIXTURES);
test('从入口标记可达模块', () => {
assert.deepEqual(result.reachable.sort(), ['./lib.js', './main.js', './util.js']);
});
test('删除未被使用的导出', () => {
assert.deepEqual(result.removed.sort(), ['alsoUnused', 'dead', 'unused']);
});
test('保留被使用的导出', () => {
assert.deepEqual(result.kept.sort(), ['helper', 'main', 'used']);
});
test('处理后源码中不再出现死导出', () => {
assert.match(result.code['./lib.js'], /export const used/);
assert.doesNotMatch(result.code['./lib.js'], /unused/);
assert.doesNotMatch(result.code['./util.js'], /dead/);
});
test('import 子句只保留用到的名字', () => {
assert.match(result.code['./main.js'], /import \{ used \} from '\.\/lib\.js';/);
assert.match(result.code['./main.js'], /import \{ helper \} from '\.\/util\.js';/);
});
test('run 输出可达模块、删除与保留列表', () => {
const out = [];
run((s) => out.push(s));
assert.equal(out.length, 6);
assert.match(out[1], /alsoUnused/);
});