假设您有相对文件引用(例如,使用JS):
const db = require('../../models/index');
在大型项目中,找到必要依赖项的相对路径很麻烦。是否有一种崇高的文本插件,还是一种无需手动找出路径即可引用相对依赖项的首选方法?
由于您不使用babel,我可能会选择这样的东西:
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
没有特殊处理的别名的常规路径应直接进入常规require
而无需修改。
而且我也不想覆盖内置的require
,这就是为什么我创建了全局requirex
的原因。从理论上讲,您可以覆盖,但...喜欢。