示例工程 20-amd-requirejs
20-amd-requirejs/02-paths-shim/main.test.mjs
点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
import vm from 'node:vm';
const here = dirname(fileURLToPath(import.meta.url));
test('shim 把全局 Legacy 作为 legacy 模块注入', () => {
const registry = new Map();
const context = vm.createContext({
define(name, deps, factory) {
registry.set(name, { deps, factory });
},
});
vm.runInContext(readFileSync(join(here, 'dist-amd', 'use-legacy.js'), 'utf8'), context);
const mod = registry.get('use-legacy');
assert.deepEqual([...mod.deps], ['legacy']);
const result = mod.factory({ triple: (n) => n * 3 });
assert.equal(result.value, 6);
const bootstrap = readFileSync(join(here, 'dist-amd', 'bootstrap.js'), 'utf8');
assert.ok(bootstrap.includes("paths: {"), '配置里有 paths');
assert.ok(bootstrap.includes("exports: 'Legacy'"), 'shim 指向全局 Legacy');
});