1

Assume that you have a relative file reference (using JS for example):

const db = require('../../models/index');

In large projects, it's cumbersome to locate the relative paths of necessary dependencies. Is there either a sublime text plugin or a preferred way to reference relative dependencies without manually figuring out the path?

jamesdlivesinatree
  • 1,016
  • 3
  • 11
  • 36
  • 1
    If you use babel, there are [plugins](https://www.npmjs.com/package/babel-plugin-root-import) for rooting paths, as well as for creating [aliases](https://www.npmjs.com/package/babel-plugin-module-resolver). I think these tools are "transpile-time." If you're not using babel, you could probably write a custom version of require that has some way of detecting custom path aliases or does searching or something – David784 Feb 13 '20 at 19:12
  • Not using babel unfortunately :/ ..this is specifically in reference to a node project, but that's a good suggestion. – jamesdlivesinatree Feb 14 '20 at 17:01

1 Answers1

0

Since you're not using babel, I'd probably go with something like this:

const $path = require('path');
const rxTilde = /^~\/?/;
const rxDollar = /^\$(\w+)\/(.*)/;

global.requirex = path => {
  let finalPath = path; // default to entered path
  const rpath = $path.dirname(require.main.filename); // get path of main/root module
  if (rxTilde.test(path)) finalPath = $path.join(rpath, path.replace(rxTilde, '')); // use ~ tilde as "rooted" path
  else if (rxDollar.test(path)) { // use $name for special aliases
    const [, dpath, endPath] = rxDollar.exec(path);
    if (dpath === 'asdf') finalPath = $path.join(rpath, 'my/special/path', endPath);
  }
  // console.log(finalPath);
  return require(finalPath);
};

// run from directory: /home/user/www/test/
const a1 = requirex('~/my/path/to/module');
//>> /home/user/www/test/my/path/to/module
const a2 = requirex('$asdf/other-module');
//>> /home/user/www/test/my/special/path/other-module

Regular paths that don't have specially handled aliases should just "fall through" to the regular require without modification.

Also I wouldn't want to override the built in require, which is why I created a global requirex instead. In theory you could probably override, but...yikes.

David784
  • 7,031
  • 2
  • 22
  • 29