const fs = require('fs');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
class BuildTimePlugin {
apply(compiler) {
const buildTime = +new Date()
compiler.hooks.beforeCompile.tapAsync('BuildTimePlugin', (params, callback) => {
const json = JSON.stringify({ buildTime });
const filePath = path.join('./public', 'buildTime.json');
fs.writeFile(filePath, json, { flag: 'w' }, callback);
});
compiler.hooks.beforeCompile.tapAsync('BuildTimePlugin', (compilation, callback) => {
const scriptContent = `window.buildTime = ${buildTime};`;
const scriptPath = path.join('./public', 'buildTime.js');
fs.writeFile(scriptPath, scriptContent, { flag: 'w' }, callback);
});
compiler.hooks.compilation.tap('BuildTimePlugin', (compilation) => {
HtmlWebpackPlugin.getHooks(compilation).beforeAssetTagGeneration.tapAsync(
'BuildTimePlugin',
(data, cb) => {
data.assets.js.unshift('/public/buildTime.js');
cb(null, data);
}
);
});
}
}
module.exports = BuildTimePlugin;
// 使用方式(
"html-webpack-plugin": "^5.5.3" 版本要更新,不然编译报错
)
const BuildTimePlugin = require('./plugin/buildTimePlugin');
plugins.push(new BuildTimePlugin())
// 页面中检查版本
fetch(location.origin+ '/buildTime.json').then(response => response.json()).then((data) => {
console.log(data);
if(data.buildTime > window.buildTime ) {
// 当前不是最新,需要提示刷新
}
})
标签:vue,const,部署,buildTime,fs,json,添加,BuildTimePlugin,data From: https://www.cnblogs.com/zerofan/p/17827377.html