knoll
knoll

Reputation: 295

Node/Express File Paths

I've got a Node/Express app built using a similar structure to this:

/lib
  coolStuff.js
/routes
  funRoute.js
/views
  sickView.hbs
app.js

Until now, when I wanted to reference something from /lib/coolStuff.js in /routes/funRoute.js, I'd write something like this:

var coolStuff = require('../lib/coolStuff');

I'm pretty sure relative paths are a bad idea in this situation. What's a better way to reference that file?

Upvotes: 1

Views: 1170

Answers (1)

bentesha
bentesha

Reputation: 948

You can use an npm package called module-alias

npm install module-alias --save

Then in your index.js file (assuming it is your startup file) configure your module aliases as follows:

const moduleAlias = require('module-alias');
moduleAlias.addAliases({
  '@': __dirname,  //Your project root
  '@lib': __dirname + '/lib', //Path to your lib folder
  '@routes': __dirname + '/routes' //Path to your routes folder
});

Then in the rest of your application, just load modules as follows:

const routes = require('@routes');
const coolStuff = require('@lib/coolStuff');
const app = require('@/app');

Relative routes sucks for one big reason, that if you move a file, you will need to change your require path otherwise your code will break.

One big setback with this approach is that the code autocompletion will fail to work, as your IDE will not be able to know how to locate the imported package.

If you can live without code autocompletion, it just can't get better than that.

Upvotes: 2

Related Questions