forked from terpiljenya/import-glob
-
Notifications
You must be signed in to change notification settings - Fork 10
/
index.js
103 lines (85 loc) · 2.82 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
var glob = require("glob");
var path = require("path");
var fs = require("fs");
var loaderUtils = require("loader-utils");
function walkUpToFindNodeModulesPath(context) {
var tempPath = path.resolve(context, "node_modules");
var upDirPath = path.resolve(context, "../");
if (fs.existsSync(tempPath) && fs.lstatSync(tempPath).isDirectory()) {
return tempPath;
} else if (upDirPath === context) {
return undefined;
} else {
return walkUpToFindNodeModulesPath(upDirPath);
}
}
function isNodeModule(str) {
return !str.match(/^\./);
}
module.exports = function (source) {
this.cacheable && this.cacheable(true);
var self = this;
var regex = /@?import + ?((\w+) +from )?([\'\"])(.*?);?\3/gm;
var importModules = /import +(\w+) +from +([\'\"])(.*?)\2/gm;
var importFiles = /import +([\'\"])(.*?)\1/gm;
var importSass = /@import +([\'\"])(.*?)\1/gm;
var resourceDir = path.dirname(this.resourcePath);
var nodeModulesPath = walkUpToFindNodeModulesPath(resourceDir);
var loaderOptions = Object.assign({}, loaderUtils.getOptions(this));
function replacer(match, fromStatement, obj, quote, filename) {
var modules = [];
var withModules = false;
if (!filename.match(/\*/)) return match;
if (loaderOptions.alias) {
Object.entries(loaderOptions.alias).some((args) => {
var alias = args.alias;
var repl = args.repl;
if (filename.startsWith(alias)) {
filename = filename.replace(alias, repl);
return true;
}
});
}
var globRelativePath = filename.match(/!?([^!]*)$/)[1];
var prefix = filename.replace(globRelativePath, "");
var cwdPath;
if (isNodeModule(globRelativePath)) {
if (!nodeModulesPath) {
self.emitError(new Error("Cannot find node_modules directory."));
return match;
}
cwdPath = nodeModulesPath;
} else {
cwdPath = resourceDir;
}
var result = glob
.sync(globRelativePath, {
cwd: cwdPath,
})
.map((file, index) => {
var fileName = quote + prefix + file + quote;
if (match.match(importSass)) {
return "@import " + fileName;
} else if (match.match(importModules)) {
var moduleName = obj + index;
modules.push(moduleName);
withModules = true;
return "import * as " + moduleName + " from " + fileName;
} else if (match.match(importFiles)) {
return "import " + fileName;
} else {
self.emitWarning('Unknown import: "' + match + '"');
}
})
.join("; ");
if (result && withModules) {
result += "; var " + obj + " = [" + modules.join(", ") + "]";
}
if (!result) {
self.emitWarning('Empty results for "' + match + '"');
}
return result;
}
var res = source.replace(regex, replacer);
return res;
};