-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
60 lines (48 loc) · 1.71 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
const HtmlWebpackPlugin = require("../virgoui/node_modules/html-webpack-plugin");
const pluginName = "RemWebpackPlugin";
class RemWebpackPlugin {
static defaultOptions = {
root: 100,
rootWidth: 750,
maxWidth: 750,
};
constructor(options = {}) {
this.options = { ...RemWebpackPlugin.defaultOptions, ...options };
this.remStr = `
<script>
(function () {
function setRem() {
var rootFontSize = ${this.options.root};
var rootClientWidth = ${this.options.rootWidth};
var ratio = rootClientWidth / rootFontSize;
var clientWidth = window.document.documentElement.clientWidth;
console.log(clientWidth)
clientWidth = clientWidth < ${this.options.maxWidth} ? clientWidth : ${this.options.maxWidth};
document.documentElement.style.fontSize = clientWidth / ratio + "px";
}
setRem();
window.addEventListener("resize", setRem);
})();
</script>
`;
}
apply(compiler) {
compiler.hooks.compilation.tap(pluginName, (compilation) => {
let HtmlWebpackHooksTap =
compilation.hooks &&
compilation.hooks.htmlWebpackPluginAfterHtmlProcessing;
if (!HtmlWebpackHooksTap) {
HtmlWebpackHooksTap =
HtmlWebpackPlugin.getHooks(compilation).beforeEmit;
}
HtmlWebpackHooksTap.tap(pluginName, (data, callback) => {
data.html = data.html.replace(/\r\n/g, "").replace(
/<meta.+name="viewport".+\/>/gi,
(str) => str + this.remStr
);
callback && callback(null, data);
});
});
}
}
module.exports = RemWebpackPlugin;