博客 / 詳情

返回

CMS規範中require方法的簡易實現

簡單來説幾個步驟

  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

user avatar xiangjiaochihuanggua 頭像 yilezhiming 頭像 waweb 頭像 mmmy_a 頭像 fatdoge1217 頭像
5 位用戶收藏了這個故事!

發佈 評論

Some HTML is okay.