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!
var librarypath = '/Users/me/projects/library/';
// or if you prefer...
// var librarypath = '../../../../../library/';
var foo = require(librarypath + 'foo.js');
... or dressed up a bit more ...
function requirelib(lib){ return require('/Users/me/projects/library/'+lib+'.js'); }
var foo = requirelib('foo');
var bar = requirelib('bar');
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.