-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathalias.js
67 lines (61 loc) · 1.88 KB
/
alias.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
const path = require('path');
// js
const REQUIRE_REGEX = /require\(['"](.*?)['"]\)/g;
const JS_IMPORT_FROM = /from\s+['"](.*?)['"]/g;
const JS_IMPORT = /import\s+['"](.*?)['"]/g;
// wxml
const SRC_REGEX = /src=['"](.*?)['"]/g;
// css
const CSS_REGEX = /@import\s+['"](.*?)['"]/g;
let keysPattern;
let opt;
let filePath;
function setKeysPatten(options) {
options = options || {};
keysPattern = keysPattern || new RegExp(`^(${Object.keys(options).join('|')})`);
}
function replaceCallback(match, subMatch) {
if (keysPattern.test(subMatch)) {
const indexEnd = subMatch.indexOf('/') === -1 ? subMatch.length : subMatch.indexOf('/');
const key = subMatch.substring(0, indexEnd);
if (!opt[key]) {
return match;
}
const url = path.join(opt[key], subMatch.slice(indexEnd));
return match.replace(
subMatch,
path.relative(filePath, url).replace(/\\/g, '/').replace(/^\.\.\//, '')
);
} else {
return match;
}
}
module.exports = function alias(options, content, _filePath) {
opt = options = options || {};
filePath = _filePath;
setKeysPatten(options);
switch (path.extname(_filePath)) {
case '.js':
case '.wxs':
case '.ts':
content = content.replace(JS_IMPORT_FROM, replaceCallback);
content = content.replace(JS_IMPORT, replaceCallback);
content = content.replace(REQUIRE_REGEX, replaceCallback);
break;
case '.wxml':
content = content.replace(SRC_REGEX, replaceCallback);
break;
case '.styl':
case '.stylus':
case '.less':
case '.sass':
case '.scss':
case '.css':
case '.wxss':
content = content.replace(CSS_REGEX, replaceCallback);
break;
default:
break;
}
return content;
};