示例工程 11-commonjs
11-commonjs/02-exports-reassign/main.js
点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。
// main.js —— exports 重新赋值为什么无效
// exports 只是 module.exports 的初始别名;重新赋值只改局部变量。
export function createRuntime(factories) {
const cache = new Map();
function require(id) {
if (cache.has(id)) return cache.get(id).exports;
const factory = factories[id];
if (!factory) throw new Error(`Cannot find module '${id}'`);
const module = { exports: {} };
cache.set(id, module);
factory(module, module.exports, require);
return module.exports;
}
return { require, cache };
}
export const FACTORIES = {
'./bad': (module, exports) => {
exports = { a: 1 }; // 断开别名,模块值仍是空对象
},
'./good': (module, exports) => {
exports.a = 1; // 改的是同一个对象
},
'./replace': (module) => {
module.exports = { b: 2 }; // 正确:改 module.exports
},
'./mixed': (module, exports) => {
exports.a = 1; // 写进旧对象
module.exports = { b: 2 }; // 整体替换,a 丢失
},
'./reassignBoth': (module, exports) => {
module.exports = exports = { c: 3 }; // 同时更新两者,有效但少见
},
};
export function run(log = console.log) {
const { require } = createRuntime(FACTORIES);
const rows = [
['exports = {a:1}', JSON.stringify(require('./bad'))],
['exports.a = 1', JSON.stringify(require('./good'))],
['module.exports = {b:2}', JSON.stringify(require('./replace'))],
['先 exports.a 再整体替换', JSON.stringify(require('./mixed'))],
['module.exports = exports = {...}', JSON.stringify(require('./reassignBoth'))],
];
log('场景 => 模块值');
for (const [label, value] of rows) log(`${label} => ${value}`);
log('-'.repeat(50));
log('要点:require 返回 module.exports;exports 只是它的初始别名,重新赋值不会改变模块值。');
return rows;
}