Absolute paths & require()

转载:https://coderwall.com/p/th6ssq/absolute-paths-require

A quick one:

Normally, when referencing a file with require() a relative path is used. This path must reflect the position of the current file within your site's directory structure.

However, I'd rather use an absolute path based only on my site's top-level directory, and not on whichever file I'm currently in.

So, I include this snippet at the top of my main.js:

global.base_dir = __dirname;
global.abs_path = function(path) {
  return base_dir + path;
}
global.include = function(file) {
  return require(abs_path('/' + file));
}

Now when you're in a file, instead of writing something like this:

require('../../../lib/Utils.js');

You can write this:

include('lib/Utils.js');

Not only is this more readable, you also don't have to remember where in the file hierarchy you are when you'd like to include something.

Another benefit is that you won't have to update any paths if you move a file containing an include().

Lastly, when you need to get the full path to a file (perhaps for use with the fs module) you can use the global function:

abs_path('lib/Utils.js');

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值