自定义plugin
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();
vue router 添加
直接导入到html中是只有一次请求效果,所以需要添加到router切换中
router.beforeEach((to, from, next) => {
if (to.path) {
if (window._hmt) {
window._hmt.push(['_trackPageview', '/#' + to.fullPath]);
}
}
next();
});
webpack 自定义插件
compile
compiler是webpack的'编译器'引用; 所以compiler.plugin('compile')就代表:当编译器监听到compile事件时,我们应该做些什么
compiler.plugin("compile", function(params) {
console.log("The compiler is starting to compile...");
});
compilation
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...
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。