简略来说几个步骤
- 读取要加载的文件内容
- 执行文件内容
- 给执行后的后果包一层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