当前位置: 首页 > 后端技术 > Node.js

noader,实现nodejs模块的自动加载

时间:2023-04-03 20:33:55 Node.js

本人不是很熟练,一直想搞点东西。在前言中,如果你要用nodejs开发一个经典的MVC框架程序,首先要解决的问题就是自动加载。PHP有自动加载规范,可以实现类的自动加载。nodejs虽然有模块require,但是在实际项目中require项目文件的各种路径还是很麻烦的,所以创建了这个npm模块。Modulenoader:nodejs+loader的统称。项目地址:https://github.com/yafoo/noader安装npminoader使用constnoader=require('noader');常量装载机=noader();执行noader()函数后,会返回一个当前模块目录,它是根目录的rootloader。此加载器将使用点或方括号根据文件路径自动加载模块,如js对象。如果要加载的模块不存在,则返回undefined。如果要加载的模块不存在是一个class文件,访问class属性会自动生成一个class实例并调用该实例的属性,该实例是一个单例。Noader函数参数,第一个参数是根加载目录,可以是绝对地址也可以是相对地址。如果不输入,默认使用调用函数的模块目录作为根目录。以下参数用作类模块自动实例化时的参数。假设项目结构如下├──test│├──app││└──module││└──a.js│├──app2││└──b.js│└──index.jsa.js模块代码module.exports={prop:'propa',fun:function(str){this.prop=str;返回this.prop;}}b.js模块代码module.exports=class{constructor(str){this.str=str;}fun(str){this.str=str;返回这个.str;}self(){返回这个;}}index.js模块测试代码constnoader=require('noader');constloader=noader();console.log(loader.app.module.a);//对象:aconsole.log(loader.app.module.a.prop);//字符串:'propa'console.log(loader.app.module.a.fun('test1'));//字符串:'test1'console.log(loader.app2.b);//类:bconsole.log(loader.app2.b===loader.app2.b);//布尔值:trueconsole.log(loader.app2.b.str);//Undefinedconsole.log(loader.app2.b.fun('test2'));//字符串:'test2'console.log(loader.app2.b.$map.instance);//类:binstanceconsole.log(loader.app2.b.$map.instance===loader.app2.b.$map.instance);//布尔值:trueconsole.log(loader.app2.b.$map.is_class);//布尔值:trueconstc=newloader.app2.b('test3');console.log(c);//类b实例:cconsole.log(c.str);//字符串:'test3'console.log('--------------------------------');constloader2=noader(__dirname+'/../','test4');console.log(loader2.test.app.module.a);//对象:aconsole.log(loader2.test.app2.b);//类:bconsole.log(loader2.test.app2.b.str);//字符串:'test4'console.log('--------------------------------');控制台。日志(loader2.test.app2.b===loader.app2.b);//Boolean:false(因为类是代理对象)console.log(loader2.test.app2.b.$map.instance===loader.app2.b.$map.instance);//布尔值:falseconsole.log(loader2.test.app2.b.$map.path);//b执行程序的绝对路径#nodeindex.js{prop:'propa',fun:[Function:fun]}propatest1[Function]trueundefinedtest2{str:'test2'}truetrue{str:'test3'}test3------------------------------{prop:'test1',fun:[Function:fun]}[Function]test4----------------------------------falsefalseD:\wwwroot\noader\test/app2/b/也可以快速运行模块测试脚本gitclonehttps://github.com/yafoo/noader.gitnpminpmtest终于搞定了它这个加载器可以根据项目目录结构任意访问项目文件。很方便,就是不知道安全性如何。希望有思考的大神们可以指点一下。最后,我会把我的开发基于这个加载器开发的mvc框架。博客链接:https://me.i-i.me/article/12.html