vue+vite项目添加项目发版时间

20 阅读1分钟

记录需求,要求项目发布时带上当时打包的时间。

1.在utils目录新建index.js

//格式化时间
function formatDate (timer) {
    let year = timer.getFullYear();
    let month = timer.getMonth() + 1; // 由于月份从0开始,因此需加1
    if (month < 10) month = "0" + month;
    let day = timer.getDate();
    if (day < 10) day = "0" + day;
    let hour = timer.getHours();
    if (hour < 10) hour = "0" + hour;
    let minute = timer.getMinutes();
    if (minute < 10) minute = "0" + minute;
    let second = timer.getSeconds();
    if (second < 10) second = "0" + second;
    return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
  }
export default formatDate

2.在vite.config.js中引入格式化当前时间

import formatDate from './src/utils/index';
const buildTime = formatDate(new Date());

如下:

image.png

在defineConfig中新增

define: {
    'import.meta.env.VITE_BUILD_TIME': JSON.stringify(buildTime)
}

如下: image.png 项目根目录新增.env环境变量文件,写上自定义变量名

VITE_BUILD_TIME = ''

image.png

在App.vue新增日志

const buildTime = import.meta.env.VITE_BUILD_TIME;
console.log('本次发版时间:', buildTime);

image.png 这样项目打包后就会记录打包的时间,浏览器F12即可。

image.png