Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

How do you make packages & variables available in all the modules of a node app without cluttering global scope?

Hello All,

I built a node application recently and have decided to modularize it for practice, which is easy enough.

I'm requiring all the dependencies and executing the application with a function in the app.js file (there's not much else in that file anymore), which means that all of the modular file functions should take place down the scope-chain and have access to the packages and variables required in app.js, correct?

However, the package methods and variables defined and required in app.js are throwing errors as undefined. This means the modular files I'm creating don't have access to the variables and packages required in my app.js file.

The program works fine in one large app file. The code works fine if I declare all the dependencies and variables in app.js as globals. And the code will work if I require the packages in every file.

...However, all of these solutions defeat the purpose of modular code patterns...

How do you make packages and variables available in all the modules of a node application without cluttering the global scope?

1 Answer

Casey Ydenberg
Casey Ydenberg
15,622 Points

Requiring all your dependencies in app.js is not really modularizing. Ideally you'd want to require your dependencies from the files where they are needed.

Sometimes this doesn't work; dependencies need configurations or the dependency exposes an object that you need a single instance of throughout your application. In these cases you have a couple of options: you can either create a utilities file that you then require as needed (e.g. require('./utils').emitter) or you can configure your modules to return a function that wraps around what you're really trying to expose. You can then pass in the dependencies/utilities that module will need as arguments.