CommonJS 模块化规范
定义¶
https://github.com/nodejs/node/blob/master/lib/internal/modules/cjs/loader.js
- commonJS 是一个运行时解析的规范
- require 不是关键字,它类似一个全局函数
实现一个 customRequire¶
- moduleA.js
console.log('this is module A');
module.exports = 123;
- module.js
const moduleA = require('./moduleA.js');
console.log('this is module', moduleA);
- index.js
const vm = require('vm');
const path = require('path');
const fs = require('fs');
function customRequire(filePath) {
// 1. 读取文件内容
const absPath = path.resolve(__dirname, filePath);
const content = fs.readFileSync(absPath, 'utf-8');
const wrapper = [
'(function(require, module, exports) {',
'})'
];
// 2. 将字符串变成可执行函数
const wrappedContent = wrapper[0] + content + wrapper[1];
const script = new vm.Script(wrappedContent, {
filename: 'index.js'
});
const func = script.runInThisContext();
// 3. 声明 module.exports,执行函数
const module = {
exports: {}
};
func(customRequire, module, module.exports);
return module.exports;
}
customRequire('./module.js');