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.