forked from TheLarkInn/angular2-template-loader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
53 lines (44 loc) · 1.92 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
var loaderUtils = require("loader-utils");
// using: regex, capture groups, and capture group variables.
var templateUrlRegex = /templateUrl\s*:(\s*['"`](.*?)['"`]\s*([,}]))/gm;
var stylesRegex = /styleUrls *:(\s*\[[^\]]*?\])/g;
var stringRegex = /(['`"])((?:[^\\]\\\1|.)*?)\1/g;
function replaceStringsWithRequires(string) {
return string.replace(stringRegex, function (match, quote, url) {
if (url.charAt(0) !== ".") {
url = "./" + url;
}
return "require('" + url + "')";
});
}
module.exports = function(source, sourcemap) {
var config = {};
Object.assign(config, loaderUtils.getOptions(this));
var styleProperty = 'styles';
var templateProperty = 'template';
if (config.keepUrl === true) {
styleProperty = 'styleUrls';
templateProperty = 'templateUrl';
}
this.cacheable();
var newSource = source.replace(templateUrlRegex, function (match, url) {
// replace: templateUrl: './path/to/template.html'
// with: template: require('./path/to/template.html')
// or: templateUrl: require('./path/to/template.html')
// if `keepUrl` query parameter is set to true.
return templateProperty + ":" + replaceStringsWithRequires(url);
})
.replace(stylesRegex, function (match, urls) {
// replace: stylesUrl: ['./foo.css', "./baz.css", "./index.component.css"]
// with: styles: [require('./foo.css'), require("./baz.css"), require("./index.component.css")]
// or: styleUrls: [require('./foo.css'), require("./baz.css"), require("./index.component.css")]
// if `keepUrl` query parameter is set to true.
return styleProperty + ":" + replaceStringsWithRequires(urls);
});
// Support for tests
if (this.callback) {
this.callback(null, newSource, sourcemap)
} else {
return newSource;
}
};