Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
NodeJS require concept for local modules

NodeJS require concept for local modules

The problem

As your NodeJS app grows bigger, the file structure tends to go 3 to even 5 layers deep. The problem now is as you require local modules you created, you'll have to write them in this way:

const myModule = require('../../../my/module');

This can become an awful developer experience.

The simplest solution I thought of:

on the top of your server.js or whatever the filename is of that which you run first when you startup your nodejs application.

const path = require('path');
global._require = module => require(path.join(__dirname, module));

//.. rest of your codes

Then on a/very/far/away/module.js:

// coming from /root/libs/validator
const validator = _require('libs/validator');
// coming from the /root/constanst
const { validListOfThings } = _require('constants');

The file structure would look like:

|- a
|  |- very
|  |  |- far
|  |  |  |- away
|  |  |  |  |- module.js
|- libs
|  |- validator.js
|- server.js
|- constants.js

You can now use _require for your local modules, and you can still use require for your node_modules.

Why use this solution?

  1. This is not a hacky solution that suggests you mess with a built-in function of node that might change in future version, in short, it's version independent and might even work with previous versions of node with the assumption that path and require on those version works the same way, unless that version of node implements _require as a built-in function, if it does, then simply change the name? ¯_(ツ)_/¯
  2. It works globally anywhere in your NodeJS app.
  3. You don't have to manually do something like require(`${basepath}/my/module.js`).
  4. Since we are using path module, it should work on other OS too. (Tell me if it doesn't, I'd like to figure out why).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment