示例工程 21-commonjs-snapshot
21-commonjs-snapshot/02-exports-reassign/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('重新赋值 exports 不会改变 module.exports', () => {
const module = { exports: {} };
const context = vm.createContext({ module, exports: module.exports });
const source = readFileSync(join(here, 'dist-cjs', 'reassign.js'), 'utf8');
vm.runInContext(source, context);
assert.equal(module.exports['value'], 1, 'module.exports 仍是第一次写入的对象');
assert.equal(context.exports['value'], 2, '局部 exports 指向了新对象');
assert.notEqual(context.exports, module.exports);
});