- Posted by liammclennan on July 17, 2011
The obvious and default way of resolving dependencies in JavaScript modules is to do so as needed. In other words, I request a dependency at the point where it is required. The effect of this is to make all modules responsible for resolving the dependencies that they require and to make it nearly impossible to test modules in isolation. Such code often looks like this:
My current preferred solution is to write modules that expose a sinlge variable which is a function that returns the actual module. The input to the function is the modules dependencies. At runtime the function is called with no arguments - so it resolves the dependencies internally. For testing, the function is passed mock dependencies. Here is a module that supports dependency injection:
and an example of using the module with real and fake dependencies:
The examples given use the node.js module syntax, but the pattern works for require.js and probably some other JavaScript module frameworks. This is what I came up with because I could not find any existing work on dependency injection for JavaScript modules. If you can point me to any alternatives I would appreciate it.