Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS and Javascript (requirejs) dependency injection

I am currently using requirejs to manage module js/css dependencies. I'd like to discover the possibilities of having node do this via a centralized config file. So instead of manually doing something like

define([    
'jquery'
'lib/somelib'
'views/someview']

within each module.

I'd have node inject the dependencies ie

require('moduleA').setDeps('jquery','lib/somelib','views/someview')

Anyway, I'm interested in any projects looking at dependency injection for node.

thanks

like image 736
Chin Avatar asked Dec 02 '11 06:12

Chin


1 Answers

I've come up with a solution for dependency injection. It's called injectr, and it uses node's vm library and replaces the default functionality of require when including a file.

So in your tests, instead of require('libToTest'), use injectr('libToTest' { 'libToMock' : myMock });. I wanted to make the interface as straightforward as possible, with no need to alter the code being tested. I think it works quite well.

It's just worth noting that injectr files are relative to the working directory, unlike require which is relative to the current file, but that shouldn't matter because it's only used in tests.

like image 180
Nathan MacInnes Avatar answered Oct 07 '22 01:10

Nathan MacInnes