配置打包后js文件名,解决更新后浏览器缓存问题

145 阅读2分钟

vue.config.js

"use strict";
const path = require("path");
const defaultSettings = require("./src/settings.js");

function resolve(dir) {
  return path.join(__dirname, dir);
}

const name = defaultSettings.title || "FundPersonas Web"; // page title 
const port = process.env.port || process.env.npm_config_port || 9528; // dev port
const timeStamp = new Date().getTime() 
module.exports = { 
  publicPath: process.env.VUE_APP_CONTEXT,
  outputDir: 'dist',
  assetsDir: 'static',
  lintOnSave: process.env.NODE_ENV === 'development',
  productionSourceMap: false,
  devServer: {
    port: port,
    open: true,
    overlay: {
      warnings: false,
      errors: true
    } 
  },
  configureWebpack: { 
    name: name,
    resolve: {
      alias: {
        '@': resolve('src')
      }
    },
    externals: {
      './cptable': 'var cptable'
    },
    output: {
      // 不加会报错chunk src_views_AI_know_knowledgeList_vue [mini-css-extract-plugin]Conflicting order. Following module has been added:
      // 输出重构 打包编译后的js文件名称,添加时间戳.
      filename: `js/js[name].${timeStamp}.js`,
      chunkFilename: `js/chunk.[id].${timeStamp}.js`

      // 也可以使用hash
      // filename: `js/js[name].[hash].js`,
      // chunkFilename: `js/chunk.[id].[hash].js`,
    }
  },
  css: {
    extract: {
      // 打包后css文件名称添加时间戳
      filename: `css/[name].${timeStamp}.css`,
      chunkFilename: `css/chunk.[id].${timeStamp}.css`
    }
  },
  chainWebpack(config) {
    config.plugins.delete("preload"); // TODO: need test
    config.plugins.delete("prefetch"); // TODO: need test

    // 忽略的打包文件
    config.externals({
      vue: "Vue",
      "vue-router": "VueRouter",
      vuex: "Vuex",
      axios: "axios",
      "element-ui": "ELEMENT"
    });
    // set svg-sprite-loader
    config.module
      .rule("svg")
      .exclude.add(resolve("src/icons"))
      .end();
    config.module
      .rule("icons")
      .test(/\.svg$/)
      .include.add(resolve("src/icons"))
      .end()
      .use("svg-sprite-loader")
      .loader("svg-sprite-loader")
      .options({
        symbolId: "icon-[name]"
      })
      .end();

    // set preserveWhitespace
    config.module
      .rule("vue")
      .use("vue-loader")
      .loader("vue-loader")
      .tap(options => {
        options.compilerOptions.preserveWhitespace = true;
        return options;
      })
      .end();

    config
      // https://webpack.js.org/configuration/devtool/#development
      .when(process.env.NODE_ENV === "development", config =>
        config.devtool("cheap-source-map")
      );

    config.when(process.env.NODE_ENV !== "development", config => {
      config
        .plugin("ScriptExtHtmlWebpackPlugin")
        .after("html")
        .use('script-ext-html-webpack-plugin', [
          {
            // `runtime` must same as runtimeChunk name. default is `runtime`
            inline: /runtime\..*\.js$/
          }
        ])
        .end()
      config.optimization.splitChunks({
        chunks: 'all',
        cacheGroups: {
          libs: {
            name: 'chunk-libs',
            test: /[\\/]node_modules[\\/]/,
            priority: 10,
            chunks: 'initial' // only package third parties that are initially dependent
          },
          elementUI: {
            name: 'chunk-elementUI', // split elementUI into a single package
            priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
            test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // in order to adapt to cnpm
          },
          commons: {
            name: 'chunk-commons',
            test: resolve('src/components'), // can customize your rules
            minChunks: 3, //  minimum common number
            priority: 5,
            reuseExistingChunk: true
          }
        }
      });
      config.optimization.runtimeChunk('single')
    })
  }
}

vite.config.ts

import { defineConfig, loadEnv } from 'vite';
require('dotenv').config({ path: `.env.development` });

import {
  // createViteProxy,
  getRootPath,
  getSrcPath,
  setupVitePlugins
} from './build';
// import { getServiceEnvConfig } from './.env-config';
export default defineConfig(configEnv => {
  const viteEnv = loadEnv(configEnv.mode, process.cwd()) as unknown as ImportMetaEnv;

  const rootPath = getRootPath();
  const srcPath = getSrcPath();

  // const isOpenProxy = viteEnv.VITE_HTTP_PROXY === "Y";
  // console.log(`isOpenProxy`, isOpenProxy);
  // const envConfig = getServiceEnvConfig(viteEnv);
  const BASE_URL =
    process.env.VITE_DOWN_PROXY === 'development' ? 'http://localhost:9011' : 'http://localhost:9011/fscc-kb-backend';

  const timeStamp = new Date().getTime();
  return {
    base: viteEnv.VITE_BASE_URL,
    resolve: {
      alias: {
        '~': rootPath,
        '@': srcPath
      }
    },
    plugins: setupVitePlugins(viteEnv),
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: `@use "./src/styles/scss/global.scss" as *;`
        }
      }
    },

    // base: {
    // 	publicPath: "/kb-web",
    // },
    server: {
      port: 7779,
      proxy: {
        '/local': {
          target: BASE_URL,
          changeOrigin: true,
          rewrite: path => path.replace(/^\/local/, '')
        },
        // "/knowledge-base": {
        // 	// target: 'http://localhost:9011/fscc-kb-backend',
        // 	target: '/fscc-kb-backend',
        // 	changeOrigin: true,
        // 	rewrite: (path) => path.replace(/^\/knowledge-base/, ""),
        // },
        // 选项写法
        '/api': {
          target: 'https://route.showapi.com/',
          changeOrigin: true,
          rewrite: path => path.replace(/^\/api/, '')
        },
        '/chat-gpt': {
          target: 'https://bak.cwjiaoyu.cn/message',
          changeOrigin: true,
          rewrite: path => path.replace(/^\/chat-gpt/, '')
        },
        '/aiqa': {
          target: 'https://hj.fsfund.com/chat-api',
          changeOrigin: true,
          rewrite: path => path.replace(/^\/aiqa/, '')
        },
        '/opinion': {
          // target: "https://hj.fsfund.com/fund-grab",
          // target: 'http://172.30.112.130:8702',
          // target: 'http://172.30.112.93:8702',
          // target: 'http://172.30.113.199:8702',
          target: 'http://172.30.113.209:8702',
          // target: 'http://172.30.112.87:8702',
          // target: "https://hj.fsfund.com/fscc-kb-backend",
          changeOrigin: true,
          rewrite: path => path.replace(/^\/opinion/, '')
        }
      },
      hmr: {
        overlay: false
      },
      host: '0.0.0.0'
    },
    optimizeDeps: {
      include: ['@better-scroll/core']
    },
    build: {
      reportCompressedSize: false,
      sourcemap: false, // 源代码映射
      commonjsOptions: {
        ignoreTryCatch: false
      },
      rollupOptions: {
        // 输出配置
        output: {
          // 输出的文件自定义命名
          chunkFileNames: `js/[name]-[hash].${timeStamp}.js`,
          entryFileNames: `js/[name]-[hash].${timeStamp}.js`,
          assetFileNamesL: `[ext]/[name]-[hash].${timeStamp}.[text]`
        }
      }
    },
    esbuild: {
      charset: 'ascii'
    }
  };
});