If you’ve ever required a service in a large project you are familiar with this problem. The following solution uses absolute paths instead of relative paths to solve this problem.

In your app.js (or index.js or server.js or main.js or whatever you call your main js file in the root directory of your project) add the following function.

global.include = file => require(__dirname+'/'+file);

Now instead of figuring out how many directories you are from your lib folder and typing this out

const myService = require('../../../lib/myService');

You can simply do the following

const myService = include('lib/myService');

Shout out to amoniker for writing the article that described this solution. https://coderwall.com/p/th6ssq/absolute-paths-require

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s