假设您有一个相对文件引用(例如使用JS ):
const db = require('../../models/index');在大型项目中,定位必要依赖项的相对路径是很麻烦的。有没有一个很棒的文本插件或者更好的方式来引用相对依赖关系,而不需要手动找出路径?
发布于 2020-02-15 02:03:33
由于您没有使用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。理论上你可以重写,but...yikes。
https://stackoverflow.com/questions/60214694
复制相似问题