Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?

Root-Relative Require with -

Some folks really don't like typing ../../.., etc. There are many ways around this, but one of the simplest is to use npm's file: feature.

Assume a project that looks like this:

my-project/
├── src/
│   ├── some/
│   │   └── deeply/
│   │       └── nested/
│   │           └── module.test.js
│   ├── utils/
│   │   └── test.js
│   └── package.json
└── package.json

Let's say you wanted to reference ./src/utils/test.js from ./src/some/deeply/nested/module.test.js and you really don't want to write ../../../utils/test.js. Start off by adding - as a project dependency and set the version as file:./src/ in ./package.json:

{
    "name": "my-project",
    "dependencies": {
        "-": "file:./src/",
        "express": "^4.0.0"
    }
}

Then create a private dummy ./src/package.json file:

{
  "name": "-",
  "description": "Allow src-relative `require()`.",
  "private": true
}

You can then use - instead of ../../.. in ./src/some/deeply/nested/module.test.js:

- const { mock } = require('../../../utils/test.js');
+ const { mock } = require('-/utils/test.js');

  // success!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment