Vue项目自动设置版本号,版本号变更清空缓存

Vue项目自动设置版本号,版本号变更清空缓存

前言

项目每次打包后都需要手动改动项目版本号,这个改动每次都需要在package.json中修改version,比较麻烦,。

项目更新后文件存在缓存,需要强制刷新才能呈现更新

解决

  • 安装npm依赖

    npm install --save-dev @intervolga/[email protected] [email protected] [email protected] [email protected]
    
  • 在你的 package.json 文件中添加以下 scripts

    "scripts": {
          
          
       "version": "node ./build/version.js",
       "build": "npm run version && vue-cli-service build"
    }
    
  • 在你的项目根目录下创建 build 文件夹,并在该文件夹下创建 version.js 文件

  • version.js 文件中添加以下代码

    const fs = require('fs');
    const path = require('path');
    const moment = require('moment');
    
    const packageJsonPath = path.resolve(__dirname, '../package.json');
    const indexPath = path.resolve(__dirname, '../public/index.html');
    
    // 读取 package.json 文件
    const packageJson = fs.readFileSync(packageJsonPath, 'utf8');
    const packageData = JSON.parse(packageJson);
    
    // 获取当前的版本号
    const currentVersion = packageData.version;
    
    // 生成新的版本号
    const newVersion = moment().format('YYYYMMDDHHmmss');
    
    if (currentVersion !== newVersion) {
          
          
      // 更新 package.json 中的版本号
      packageData.version = newVersion;
      fs.writeFileSync(packageJsonPath, JSON.stringify(packageData, null, 2));
    
      // 清空缓存
      const indexHtml = fs.readFileSync(indexPath, 'utf8');
      const newHtml = indexHtml.replace(/(src|href)=(['"])([^"']+)(["'])/g, (match, p1, p2, p3, p4) => {
          
          
        let newUrl = p3;
        if (newUrl.includes('?')) {
          
          
          newUrl = newUrl.split('?')[0];
        }
        return `${
            
            p1}=${
            
            p2}${
            
            newUrl}?v=${
            
            newVersion}${
            
            p4}`;
      });
    
      fs.writeFileSync(indexPath, newHtml);
    
      console.log(`Version updated: ${
            
            currentVersion} -> ${
            
            newVersion}`);
    }
    
  • 运行 npm run build 命令来构建项目。每次构建时,版本号将会自动更新,并且缓存将会被清空

这样,每次构建时都会自动设置新的版本号,并且保证缓存的更新。请确保在每次构建之前都运行 npm run build 命令

结语

感谢读者阅读并关注博客文章,并对文章中提到的观点、建议或批评表示感谢

猜你喜欢

转载自blog.csdn.net/qq_54334713/article/details/131537248
今日推荐