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:
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.
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
You should be all set with that.