I'm trying to use requirejs in node.js but I don't like to redefine the requirejs in each file.
-
Require is built into node, no? Do you mean you don't want to have to re require other modules in every file? – Zeke Nierenberg Sep 06 '13 at 14:50
-
require is, but requirejs is not, they are not the same thing. requirejs is for client side async loader – Totty.js Sep 06 '13 at 15:28
2 Answers
You can use node.js global variables
GLOBAL.example = require('./example');
-
I've heard this is a no-no... I don't recall what the argument was exactly, but I think it was something like the fact that the only way between modules should be the module exports – Zeke Nierenberg Sep 06 '13 at 14:52
-
I heard too, but maybe this is a good case? I don't think it will work from relative loaded modules, right? – Totty.js Sep 06 '13 at 15:29
I'm only able to see two options to import modules into your files without reusing require. Global variables or Dependency Injection. Links contain the examples
Although both techniques can be useful, neither are particularly good options in this scenario. Using global variables makes your code hard to debug and reduce readability. Dependency injection will clutter up your app far more than reusing require.
The method you're using now seems to be the current common practice.
Requiring the same module over and over again isn't necessarily a bad thing. You don't need to worry about a performance hit, since modules are cached after they're first loaded and only executed once. It also makes your code more readable, since you know upfront which libraries you're using.

- 1
- 1

- 1,063
- 9
- 10