-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
99 lines (91 loc) · 2.66 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
95
96
97
98
99
'use strict';
/**
*
* @param options
* headTags | bodyTags: {
* tagName: 'style' | 'script'
* tagCode: ''
* }
* @constructor
*/
function HtmlWebpackInlineCodePlugin (options) {
options = options || {};
this.headTags = options.headTags;
this.bodyTags = options.bodyTags;
}
HtmlWebpackInlineCodePlugin.prototype.apply = function (compiler) {
var self = this;
if (compiler.hooks) {
// webpack 4 support
compiler.hooks.compilation.tap('HtmlWebpackInlineCodePlugin', function (compilation) {
if (compilation.hooks.htmlWebpackPluginBeforeHtmlGeneration) {
compilation.hooks.htmlWebpackPluginAlterAssetTags.tapAsync('HtmlWebpackInlineCodePlugin', function (htmlPluginData, callback) {
self.processTags(htmlPluginData);
callback(null);
});
} else {
// HtmlWebPackPlugin 4.x
var HtmlWebpackPlugin = require('html-webpack-plugin');
var hooks = HtmlWebpackPlugin.getHooks(compilation);
hooks.alterAssetTagGroups.tapAsync('HtmlWebpackInlineCodePlugin', function (htmlPluginData, callback) {
self.processTags(htmlPluginData);
callback(null);
});
}
});
} else {
// webpack 3 support
compiler.plugin('compilation', function (compilation) {
compilation.plugin('html-webpack-plugin-alter-asset-tags', function (htmlPluginData, callback) {
self.processTags(htmlPluginData);
callback(null, htmlPluginData);
});
});
}
};
HtmlWebpackInlineCodePlugin.prototype.processTags = function (htmlPluginData) {
var self = this;
// inline js
var scriptTag = {
tagName: 'script',
closeTag: true,
attributes: {
type: 'text/javascript'
}
};
// inline css
var styleTag = {
tagName: 'style',
closeTag: true,
attributes: {
type: 'text/css'
}
};
// head code
if (Array.isArray(self.headTags) && self.headTags.length) {
self.headTags.forEach(function (tag) {
if (tag.tagName === 'script') {
scriptTag.innerHTML = tag.tagCode;
htmlPluginData.head.push(scriptTag);
}
if (tag.tagName === 'style') {
styleTag.innerHTML = tag.tagCode;
htmlPluginData.head.push(styleTag);
}
});
}
// body code
if (Array.isArray(self.bodyTags) && self.bodyTags.length) {
self.headTags.forEach(function (tag) {
if (tag.tagName === 'script') {
scriptTag.innerHTML = tag.tagCode;
htmlPluginData.body.unshift(scriptTag);
}
if (tag.tagName === 'style') {
styleTag.innerHTML = tag.tagCode;
htmlPluginData.body.unshift(styleTag);
}
});
}
};
module.exports = HtmlWebpackInlineCodePlugin;