关于cms:CMS规范中require方法的简易实现

31次阅读

共计 798 个字符,预计需要花费 2 分钟才能阅读完成。

简略来说几个步骤

  1. 读取要加载的文件内容
  2. 执行文件内容
  3. 给执行后的后果包一层 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

正文完
 0