前言
项目部署上线,新加的效果却怎么都不生效,那个可恶的bug怎么还有,到底我的部署是不是被同事的版本覆盖了,还是因为有缓存没更新到,到底怎么快速验证现在运行着的网页是不是最新的版本呢?
其实很简单,可以在网页index.html
中的<head>
内增加一个<meta>
标签,将当前打包的时间作为其中的内容显示出来。
原理:<meta>
元素可提供有关页面的元信息(meta-information),元数据不会显示在客户端,但是会被浏览器解析。<meta>
元素通常用于指定网页的描述,关键词,文件的最后修改时间,作者及其他元数据。
方法:利用webpack中的html-webpack-plugin
插件实现自定义meta标签。
效果展示
代码
1. webpack项目
在webpack的配置文件里
module.exports = merge(baseWebpackConfig, {
plugins: [
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'index.html',
inject: true,
meta: {
builtTime: new Date().toLocaleString();
}
})
]
})
2. vuecli脚手架创建的项目
使用vuecli 4.5 版本及 5.0 版本创建 vue2 及 vue3 版本的项目可参考下面的配置
- 在 vue.config.js 配置
module.exports = defineConfig({
chainWebpack: config => {
config.plugin("html").tap(args => {
// 可以只配置只在生产环境中显示
// if (process.env.NODE_ENV === "production") {
const date = new Date();
args[0].builtTime = date.toLocaleString();
// }
return args;
});
},
});
- 在 index.html 配置
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no,viewport-fit=cover">
<% if (htmlWebpackPlugin.options.builtTime) { %>
<meta name="builtTime" content="<%= htmlWebpackPlugin.options.builtTime %>">
<% } %>
<link rel="icon" href="<%= BASE_URL %>favicon.ico">
</head>
3. vite创建的项目
使用 vite
需要安装 vite-plugin-html-config
插件,其相当于 webpack里面的 HtmlWebpackPlugin
npm i vite-plugin-html -D
或者
yarn add vite-plugin-html -D
在 vite.config.js 配置
import htmlPlugin from "vite-plugin-html-config";
export default defineConfig(({
command, mode }) => {
plugins: [
vue(),
htmlPlugin({
metas:
mode === "production"
? [
{
name: "builtTime",
content: new Date().toLocaleString(),
},
]
: [],
}),
];
});
总结
这篇博客介绍了怎么在vue项目里插入<meta>
标签,并且可以将其应用于展示打包时间,验证项目版本。
欢迎点赞+评论+收藏!