forked from fred104/webpack-import-glob-loader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
93 lines (73 loc) · 2.42 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
var glob = require("glob");
var path = require("path");
var fs = require('fs');
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);
function replacer(match, fromStatement, obj, quote, filename) {
var modules = [];
var withModules = false;
if (!filename.match(/\*/)) return match;
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;
};