-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
94 lines (76 loc) · 2.96 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/**
* @author mbenzenhoefer
* thanks to DustinJackson for delivering a frame for this plugin
* see https://github.com/DustinJackson/html-webpack-inline-source-plugin
*/
'use strict';
var assert = require('assert');
var path = require('path');
var slash = require('slash');
function HtmlWebpackDynamicLoaderPlugin (options) {
assert.equal(options, undefined, 'The HtmlWebpackDynamicLoaderPlugin does not accept any options');
}
HtmlWebpackDynamicLoaderPlugin.prototype.apply = function (compiler) {
var self = this;
// Hook into the html-webpack-plugin processing
compiler.plugin('compilation', function (compilation) {
compilation.plugin('html-webpack-plugin-alter-asset-tags', function (htmlPluginData, callback) {
if (!htmlPluginData.plugin.options.dynamicLoadResources) {
return callback(null, htmlPluginData);
}
var regexStr = this.options.dynamicLoadResources;
var result = self.processTags(compilation, regexStr, htmlPluginData);
callback(null, result);
});
});
};
HtmlWebpackDynamicLoaderPlugin.prototype.processTags = function (compilation, regexStr, pluginData) {
var self = this;
var body = [];
var head = [];
var regex = new RegExp(regexStr);
pluginData.head.forEach(function (tag) {
head.push(self.processTag(compilation, regex, tag));
});
pluginData.body.forEach(function (tag) {
body.push(self.processTag(compilation, regex, tag));
});
return { head: head, body: body, plugin: pluginData.plugin, chunks: pluginData.chunks, outputName: pluginData.outputName };
};
HtmlWebpackDynamicLoaderPlugin.prototype.processTag = function (compilation, regex, tag) {
var deferrable = false;
var originalTag;
if (tag.tagName === 'script' && regex.test(tag.attributes.src)) {
deferrable = true;
originalTag = JSON.parse(JSON.stringify(tag));
tag = {
tagName: 'script',
closeTag: true,
attributes: {
type: 'text/javascript'
}
};
} else if (tag.tagName === 'link' && regex.test(tag.attributes.href)) {
deferrable = true;
originalTag = JSON.parse(JSON.stringify(tag));
tag = {
tagName: 'style',
closeTag: true,
attributes: {
type: 'text/css'
}
};
}
if (deferrable) {
// create the tag
var tagAttributes = Object.keys(originalTag.attributes);
var tagString = "document.write('<" + tag.tagName;
for(var i = 0; i < tagAttributes.length; i++){
tagString += " " + tagAttributes[i] + "=\"" + originalTag.attributes[tagAttributes[i]] + "\"";
}
tagString += "><\/" + originalTag.tagName + ">');";
tag.innerHTML = (tag.tagName === 'script') ? tagString.replace(/(<)(\/script>)/g, '\\x3C$2') : tagString;
}
return tag;
};
module.exports = HtmlWebpackDynamicLoaderPlugin;