UNPKG

2.04 kBJavaScriptView Raw
1/*
2 MIT License http://www.opensource.org/licenses/mit-license.php
3 Author Tobias Koppers @sokra
4*/
5var htmlMinifier = require("html-minifier");
6var attrParse = require("./lib/attributesParser");
7var SourceNode = require("source-map").SourceNode;
8var loaderUtils = require("loader-utils");
9
10function randomIdent() {
11 return "xxxHTMLLINKxxx" + Math.random() + Math.random() + "xxx";
12};
13
14
15module.exports = function(content) {
16 this.cacheable && this.cacheable();
17 var query = loaderUtils.parseQuery(this.query);
18 var attributes = ["img:src"];
19 if(query.attrs !== undefined) {
20 if(typeof query.attrs === "string")
21 attributes = query.attrs.split(" ");
22 else if(Array.isArray(query.attrs))
23 attributes = query.attrs;
24 else if(query.attrs === false)
25 attributes = [];
26 else
27 throw new Error("Invalid value to query parameter attrs");
28 }
29 var root = query.root;
30 var links = attrParse(content, function(tag, attr) {
31 return attributes.indexOf(tag + ":" + attr) >= 0;
32 });
33 links.reverse();
34 var data = {};
35 content = [content];
36 links.forEach(function(link) {
37 if(!loaderUtils.isUrlRequest(link.value, root)) return;
38 do {
39 var ident = randomIdent();
40 } while(data[ident]);
41 data[ident] = link.value;
42 var x = content.pop();
43 content.push(x.substr(link.start + link.length));
44 content.push(ident);
45 content.push(x.substr(0, link.start));
46 });
47 content.reverse();
48 content = content.join("");
49 if(this.minimize) {
50 content = htmlMinifier.minify(content, {
51 removeComments: true,
52 collapseWhitespace: true,
53 collapseBooleanAttributes: true,
54 removeAttributeQuotes: true,
55 removeRedundantAttributes: true,
56 useShortDoctype: true,
57 removeEmptyAttributes: true,
58 removeOptionalTags: true
59 })
60 }
61 return "module.exports = " + JSON.stringify(content).replace(/xxxHTMLLINKxxx[0-9\.]+xxx/g, function(match) {
62 if(!data[match]) return match;
63 return '" + require(' + JSON.stringify(loaderUtils.urlToRequest(data[match], root)) + ') + "';
64 }) + ";";
65}