This repository has been archived by the owner on Aug 8, 2019. It is now read-only.
forked from tamzinblake/inject-loader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
59 lines (50 loc) · 1.7 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
var loaderUtils = require("loader-utils");
var hasOnlyExcludeFlags = function hasOnlyExcludeFlags(query) {
return Object.keys(query).filter(function(key) {
return query[key] === true;
}).length === 0;
}
var escapePath = function escapePath(path) {
return path.replace('/', '\\/')
}
var quoteRegexString = function quoteRegexString() {
return "[\'|\"]{1}";
}
var createRequireStringRegex = function createRequireStringRegex(query) {
var regexArray = [];
// if there is no query then replace everything
if (Object.keys(query).length === 0) {
regexArray.push("([^\\)]+)")
} else {
// if there are only negation matches in the query then replace everything
// except them
if (hasOnlyExcludeFlags(query)) {
Object.keys(query).forEach(function(key) {
regexArray.push("(?!" + quoteRegexString() + escapePath(key) + ")")
});
regexArray.push("([^\\)]+)")
} else {
regexArray.push("(" + quoteRegexString() + "(")
regexArray.push(Object.keys(query).map(function(key) {
return escapePath(key);
}).join("|"));
regexArray.push(")" + quoteRegexString() + ")")
}
}
// Wrap the regex to match `require()`
regexArray.unshift("require\\(")
regexArray.push("\\)")
return new RegExp(regexArray.join(""), 'g');
};
module.exports = function inject(src) {
this.cacheable && this.cacheable();
var regex = createRequireStringRegex(loaderUtils.parseQuery(this.query));
return [
'module.exports = function inject(injections) {',
'var module = {exports: {}};',
'var exports = module.exports;',
src.replace(regex, "(injections[$1] || /* istanbul ignore next */ $&)"),
'return module.exports;',
'}'
].join("\n");
}