Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Requiring same module in multiple files

I'm using Underscore.js in my project. Almost all files have this line of code: var _ = require('underscore'). The require function is synchronous so the same file is loaded each time it is used. Is this the right thing to do? Doesn't this affect performance?

Instead of this, is it okay to define a global variable in the app.js file?

_ = require('underscore')

I've read that you shouldn't use global variables, but this seems to be a valid use case.

like image 210
Elmo Avatar asked May 04 '15 19:05

Elmo


People also ask

Why we always require modules at the top of a file can we require modules inside of functions?

In the end requiring that module in a function vs at the top of a module consumes the same amount of memory, but requiring at the top of a module means it will always be ready to go when someone requests that route and you would instead factor that extra 30 minuets into your deployment time, not at 3am in the morning ...

What will happen if a feature module is imported multiple times?

If the module, once evaluated, is imported again, it's second evaluation is skipped and the resolved already exports are used. If a module is imported multiple times, but with the same specifier (i.e. path), the JavaScript specification guarantees that you'll receive the same module instance.


1 Answers

From the node.js documentation:

Modules are cached after the first time they are loaded. This means (among other things) that every call to require('foo') will get exactly the same object returned, if it would resolve to the same file.

Multiple calls to require('foo') may not cause the module code to be executed multiple times. This is an important feature. With it, "partially done" objects can be returned, thus allowing transitive dependencies to be loaded even when they would cause cycles.

So multiple calls to requiring underscore will not affect the performance as it will be loading a cached version of the module.
Source: https://nodejs.org/api/modules.html

like image 149
Ford Avatar answered Oct 03 '22 05:10

Ford