NodeJS和Javascript(requirejs)dependency injection
我目前使用requirejs来pipe理模块js / css的依赖。 我想通过一个集中的configuration文件来发现有节点做这个的可能性。 所以,而不是手动做类似的东西
define([ 'jquery' 'lib/somelib' 'views/someview']
在每个模块内。
我会有节点注入依赖关系即
require('moduleA').setDeps('jquery','lib/somelib','views/someview')
无论如何,我感兴趣的任何项目在dependency injection节点。
谢谢
我已经想出了一个dependency injection的解决scheme。 它被称为injectr ,它使用节点的vm
库并在包含文件时replacerequire
的默认function。
所以在你的testing中,不要使用require('libToTest')
, injectr('libToTest' { 'libToMock' : myMock });
使用injectr('libToTest' { 'libToMock' : myMock });
。 我想尽可能简化界面,而不需要改变正在testing的代码。 我认为它工作得很好。
值得注意的是,injectr文件是相对于工作目录而言的,与require相对于当前文件不同,但是这并不重要,因为它只用于testing。
我以前玩过的想法提供了一个替代的require
,使Node.js中的dependency injectionforms。
模块代码
例如,假设在code.js中有以下语句:fs = require('fs');
console.log(fs.readFileSync('text.txt', 'utf-8'));
如果你用node code.js
运行这个代码,那么它会打印出text.txt的内容。
注射器代码
但是,假设您有一个testing模块想抽象出文件系统。
你的testing文件test.js可能看起来像这样:
var origRequire = global.require; global.require = dependencyLookup; require('./code.js'); function dependencyLookup (file) { switch (file) { case 'fs': return { readFileSync: function () { return "test contents"; } }; default: return origRequire(file); } }
如果你现在运行node test.js
,它将打印出“ testing内容 ”,即使它包含code.js。
我也写了一个模块来完成这个,它被称为rewire 。 只需使用npm install rewire
然后:
var rewire = require("rewire"), myModule = rewire("./path/to/myModule.js"); // exactly like require() // Your module will now export a special setter and getter for private variables. myModule.__set__("myPrivateVar", 123); myModule.__get__("myPrivateVar"); // = 123 // This allows you to mock almost everything within the module eg the fs-module. // Just pass the variable name as first parameter and your mock as second. myModule.__set__("fs", { readFile: function (path, encoding, cb) { cb(null, "Success!"); } }); myModule.readSomethingFromFileSystem(function (err, data) { console.log(data); // = Success! });
我受到了内森·麦克尼斯 ( Nathan MacInnes)注入的启发,但采用了不同的方法。 我不使用vm
来评估testing模块,实际上我使用节点自己的要求。 这样你的模块就像使用require()
(除了你的修改)。 也完全支持debugging。
- 如何提供诸如数据库,logging器等依赖关系到底层库?
- 模拟Node中的依赖(主要是unit testing)
- 使用dependency injection的Node.js应用程序示例
- Javascriptdependency injection和节点中的DIP:require vs构造函数注入
- 如何解决nest.js中的DI问题?
- 在node.js中使用全局variables进行dependency injection
- 具有许多导入的节点中的dependency injection
- 节点js的 – 导入mssql模块在Angular 2项目中使用的错误:“不能解决'dns'”和“无法parsing'dgram'”
- 在Nodejs中dependency injection的模型