Is it possible to require modules from outside of your project directory without relative paths?

Viewed 3832

I'm trying to build a local library of JS modules to use in Node projects.

If a new project lives in /Users/me/projects/path/to/new/project/ and my library files are located in /Users/me/projects/library/*.js is there a way to access those files without using a relative path?

In /Users/me/projects/path/to/new/project/app.js you can require foo.js like so:

var foo = require('../../../../../library/foo') and that will work but that's clunky and if files move you'd have to update your relative paths.

I've tried requireFrom and app-module-path with no luck as they are relative to a project root.

Any ideas for how to require files from outside of your project dir?

Thanks in advance!

2 Answers

I had the same problem many times. This can be solved by using the basetag npm package. It doesn't have to be required itself, only installed as it creates a symlink inside node_modules to your base path.

const localFile = require('$/local/file')
// instead of
const localFile = require('../../local/file')

Using the $/... prefix will always reference files relative to your apps root directory.

Disclaimer: I created basetag to solve this problem

Related