Image's source
29 Sep 2015 - The Dark Side

Fixing `require` In Node.js

tl;dr: This article explains how to correctly fix your require calls in Node.js. Do not expect any dark magic tip, it is the kind of "obvious once you know it" thing. It is mostly about my personnal standards.


Try to do a bit of work in your project and you will easily end-up with require that looks like:

require('../../mydependency');

This is bad and you do not want that:

  • The same import does not look the same way everywhere.
  • Refactoring that kind of things can drive you completely crazy (because of the point above).
  • Your code does not behave as it should outside of your module (where requires will be absolute). I tend to see most of my code as modular pieces, and I want to be able to extract a module as an independent dependencies as soon as I want. This point is preventing this.

What you would like to do is to do is to be able to require from your project as if it was any other module. It forces you to explicitly use the name of your project and removes any ambiguity about where your dependency is coming from.

require('myproject/service/mydependency');

The most convenient solution to do so is to add your code folder to your path and add a root folder named according to your project.

PROJECT_ROOT/
  src/
    myproject/
      routes.js
      ...
  node_modules/
  package.json
  ...

And then you just have to include src into your path by running the following command from PROJECT_ROOT.

export NODE_PATH=$NODE_PATH:`pwd`/src

You should be all set with that.

tags: js node

Fräntz Miccoli

This blog is wrapping my notes about software engineering and computer science. My main interests are architecture, quality and machine learning but content in this blog may diverge from time to time.

Ideas are expressed here to be challenged.


About me Out Of The Comfort Zone Twitter