vue js 添加百度統計

自定義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切換中css

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事件時,咱們應該作些什麼html

compiler.plugin("compile", function(params) {
      console.log("The compiler is starting to compile...");
});

compilation

compilation('編譯器'對'編譯ing'這個事件的監聽); 在compilation事件監聽中,咱們能夠訪問compilation引用,它是一個表明編譯過程的對象引用;
咱們必定要區分compiler和compilation,一個表明編譯器實體,另外一個表明編譯過程vue

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...webpack

相關文章
相關標籤/搜索