-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
43 lines (37 loc) · 1.13 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/**
* @Author : EleanorMao(danningmao@outlook.com)
* @Date : 9/1/2017, 11:38:45 PM
*/
const path = require('path')
const Module = require('module').Module
const old_findPath = Module._findPath
const ALIAS = {}
const _pathCache = {}
Module._findPath = function (request, paths, isMain) {
var cacheKey = request + '\x00' + (paths.length === 1 ? paths[0] : paths.join('\x00'))
var _request = _pathCache[cacheKey]
if (!_request) {
_request = request
var aliasKey = Object.keys(ALIAS)
for (var i = 0, len = aliasKey.length; i < len; i++) {
var key = aliasKey[i]
if (request.startsWith(key + '/') || request === key) {
request = request.replace(key, '')
_request = path.join(ALIAS[key], request)
_pathCache[cacheKey] = _request
break
}
}
}
return old_findPath(_request, paths, isMain)
}
function setAlias (alias, path) {
if (typeof alias === 'object') {
Object.assign(ALIAS, alias)
} else if (typeof alias === 'string' && typeof path === 'string') {
ALIAS[alias] = path
} else {
throw Error('params must be object or string')
}
}
exports.setAlias = setAlias