This repository has been archived by the owner on Jan 17, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathglob-loader.js
54 lines (42 loc) · 1.45 KB
/
glob-loader.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
const glob = require("fast-glob")
const path = require("path")
const REPLACEMENT_REGEX = /.?import + ?((\w+) +from )?(['"])(.*?)\3/gm
const MODULE_IMPORT_REGEX = /import +(\w+) +from +(['"])(.*?)\2/gm
/**
* Based on `import-glob`: https://github.com/terpiljenya/import-glob
*/
module.exports = function globImport(source) {
this.cacheable()
const resourceDir = path.dirname(this.resourcePath)
function replacer(match, _, obj, quote, filename) {
const modules = []
let withModules = false
/**
* If the import filename does not have any globbing syntax, skip the
* lookup.
*/
if (!glob.isDynamicPattern(filename)) {
return match
}
let result = glob
.sync(filename, {
cwd: resourceDir,
})
.flatMap((file, index) => {
const fileName = quote + file + quote
if (match.match(MODULE_IMPORT_REGEX)) {
const moduleName = obj + index
modules.push(moduleName)
withModules = true
return "import * as " + moduleName + " from " + fileName
}
return []
})
.join("; ")
if (result && withModules) {
result += "; let " + obj + " = [" + modules.join(", ") + "]"
}
return result
}
return source.replace(REPLACEMENT_REGEX, replacer)
}