xiaoshe 2019-06-26
var track = { hasTrack: true, hash: 'xxxx' }; function HTMLWebpackMonitorPlugin(options) { this.options = options; } HTMLWebpackMonitorPlugin.prototype.apply = function(compiler) { compiler.plugin('compilation', function(compilation, options) { compilation.plugin('html-webpack-plugin-before-html-processing', function(htmlPluginData, callback) { if (track.hasTrack) { var script = ` <script> var _hmt = _hmt || []; (function() { var hm = document.createElement("script"); hm.src = "https://hm.baidu.com/hm.js?` + track.hash + `"; var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(hm, s); })(); </script> `; htmlPluginData.html = htmlPluginData.html.replace('</body>', script + '</body>'); } callback(null, htmlPluginData); }); }); }; module.exports = HTMLWebpackMonitorPlugin;
var htmlWebpackMonitorPlugin = require('./plugins/html-webpack-monitor-plugin'); new htmlWebpackMonitorPlugin();
直接导入到html中是只有一次请求效果,所以需要添加到router切换中
router.beforeEach((to, from, next) => { if (to.path) { if (window._hmt) { window._hmt.push(['_trackPageview', '/#' + to.fullPath]); } } next(); });
compiler是webpack的'编译器'引用; 所以compiler.plugin('compile')就代表:当编译器监听到compile事件时,我们应该做些什么
compiler.plugin("compile", function(params) { console.log("The compiler is starting to compile..."); });
compilation('编译器'对'编译ing'这个事件的监听); 在compilation事件监听中,我们可以访问compilation引用,它是一个代表编译过程的对象引用;
我们一定要区分compiler和compilation,一个代表编译器实体,另一个代表编译过程
compiler.plugin("compilation", function(compilation) { console.log("The compiler is starting a new compilation..."); compilation.plugin("optimize", function() { console.log("The compilation is starting to optimize files..."); }); });
详情API参考: http://www.css88.com/doc/webp...