簡單來説幾個步驟
- 讀取要加載的文件內容
- 執行文件內容
- 給執行後的結果包一層module外殼並返回
一個導出文件module.js
module.exports = function () {
return "hello world";
};
引入這個導出文件index.js
const hello = my_Require("./module.js");
console.log("hello~", hello());
my_Require實現
const { readFileSync } = require("fs");
const path = require("path");
const { Script } = require("vm");
function my_Require(filename) {
// read file
const fileContent = readFileSync(path.resolve(__dirname, filename), "utf-8");
// fileContent包含了module.exports,下面套上這層殼
const wrapperFileContent = `(function(require,module,exports){
${fileContent}
})`;
// 運行字符串
const scripts = new Script(wrapperFileContent, {
filename: "index.js",
});
const module = {
exports: {},
};
const res = scripts.runInThisContext();
res(my_Require, module, module.exports);
return module.exports;
}
global.my_Require = my_Require;
my_Require("./index.js");
運行requier.js文件
打印出hello~ hello world