Skip to content

Instantly share code, notes, and snippets.

@shannonmoeller
Created May 30, 2020 18:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shannonmoeller/510cb83b5b81ecbd446fcd3939824e4e to your computer and use it in GitHub Desktop.
Save shannonmoeller/510cb83b5b81ecbd446fcd3939824e4e to your computer and use it in GitHub Desktop.

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