-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathindex.js
42 lines (36 loc) · 1.33 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
const loaderUtils = require("loader-utils");
const path = require("path");
const os = require("os");
// using: regex, capture groups, and capture group variables.
const templateUrlRegex = /templateUrl\s*:(\s*['"`](.*?)['"`]\s*([,}]))/gm;
const stringRegex = /(['`"])((?:[^\\]\\\1|.)*?)\1/g;
function replaceStringsWithRequires(string, relativeTo) {
return string.replace(stringRegex, (match, quote, url) => {
if (relativeTo) {
url = path.join(relativeTo, url);
}
else if (url.charAt(0) !== ".") {
url = "./" + url;
}
if (os.platform() === "win32") url = url.replace(/\\/g, '\\\\');
return "require('" + url + "')";
});
}
module.exports = function(source, sourcemap) {
const options = loaderUtils.getOptions(this);
// Not cacheable during unit tests;
this.cacheable && this.cacheable();
const newSource = source.replace(templateUrlRegex, (match, url) => {
// replace: templateUrl: './path/to/template.html'
// with: template: require('./path/to/template.html')
// or: template: require('/root/app/path/template.html')
// if `relativeTo` option is set to /root/app.
return "template:" + replaceStringsWithRequires(url, options && options.relativeTo);
});
// Support for tests
if (this.callback) {
this.callback(null, newSource, sourcemap)
} else {
return newSource;
}
};