逻辑
借助nodejs的虚拟机vm模块,通过nodejs读取文件,字符串包裹文件内容一层函数,实现自定义模块参数注入
代码
需要创建3个文件来验证
- index.js 入口文件
- module.js 模块文件
- require.js 逻辑实现文件
index.js
1require('./require.js')23const result = myRequire('./module.js')4console.log('result',result)
module.js
1myExports.default = { name: "John" };2console.log('Author',Author)
require.js
1const vm = require("vm");2const path = require("path");3const fs = require("fs");45function myRequire(filename) {6 const pathToFile = path.resolve(__dirname, filename);7 const content = fs.readFileSync(pathToFile, "utf-8");8 const wrapper = [9 "(function(myRequire,myModule,myExports,__dirname,__filename,Author){",10 "})",11 ];12 const wrapperContent = wrapper[0] + content + wrapper[1];13 const script = new vm.Script(wrapperContent, {14 filename,15 });16 const myModule = {17 myExports: {},18 };19 const result = script.runInThisContext();20 result(21 myRequire,22 myModule,23 myModule.myExports,24 pathToFile,25 filename,26 "Favori"//自定义全局变量注入27 );28 return myModule.myExports;29}3031global.myRequire = myRequire;
验证
在命令行工具里执行 node index.js,输出如下结果
1[Running] node "./index.js"2Author Favori3result { default: { name: 'John' } }45[Done] exited with code=0 in 0.051 seconds
到此我们就用最简易的方式实现了一个自定义模块加载器,觉得不错的收藏一下吧!