CommonJS 模块化规范
原理解析
CommonJS 模块导出的是 module.export 这个属性。将这个属性赋值为函数,导出的就是一个函数,将这个属性赋值为一个对象,导出的就是一个对象。
下列两种写法可以说明情况:
- 导出对象
// 导出函数
// math.js
function add(x, y) {
return x + y;
}
function subtract(x, y) {
return x - y;
}
module.exports = add;
// index.js
const math = require('./01_math');
console.log(math); // math: [Function: add]
- 导出对象
// 导出对象
// math.js
function add(x, y) {
return x + y;
}
function subtract(x, y) {
return x - y;
}
module.exports = {
add,
subtract
};
// index.js
const math = require('./01_math');
console.log(math);
// math: {
// add: [Function: add],
// subtract: [Function: subtract]
// }
exports 和 module.exports
我们都知道 exports 最初始状态和 module.exports 指向的是同一个对象。但是如果对 module.exports 重新赋值之后,module.exports 和 exports 指向的就是同一个对象了。这个时候 CommonJS 模块还是会导出 module.exports 这个属性,根据这个原理,分析一下下列代码会导出什么?
代码一:
// 01_math.js
function add(x, y) {
return x + y;
}
function subtract(x, y) {
return x - y;
}
const name = 'math';
module.exports = {
add,
subtract
};
module.exports.name = name;
// index.js
const math = require('./01_math');
console.log(math);
// math: {
// add: [Function: add],
// subtract: [Function: subtract],
// name: 'math'
// }
代码二:
// 01_math.js
function add(x, y) {
return x + y;
}
function subtract(x, y) {
return x - y;
}
const name = 'math';
module.exports = {
add,
subtract
};
exports.name = name;
// index.js
const math = require('./01_math');
console.log(math);
// math: {
// add: [Function: add],
// subtract: [Function: subtract],
// }
代码三:
// 01_math.js
function add(x, y) {
return x + y;
}
function subtract(x, y) {
return x - y;
}
const name = 'math';
exports = {
add,
subtract
};
module.exports.name = name;
// index.js
const math = require('./01_math');
console.log(math);
// math: { name: 'math' }
希望能够帮到大家!