SoFunction
Updated on 2025-04-14

How to use vite to solve the problem of browser cache after front-end distribution

How to avoid browser caching problems and ensure that the browser can load the latest code every time a new version is released

Vite build tool configuration file

import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import { resolve } from 'path';
import pkg from './' assert { type: 'json' };

// Time stampconst timestamp = new Date().getTime();

export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      '@': resolve(__dirname, 'src') // Configure @ as the absolute path to the src directory    }
  },
  server: {
    host: '0.0.0.0',
  },
  build: {
    rollupOptions: {
      output: {
        manualChunks: {
          vendor: (),
        },
        chunkFileNames: ({ name }) => {
          if (name === 'vendor') {
            return `assets/js/[name]-[hash].js`; // Third-party libraries do not add timestamps          } else {
            return `assets/js/[name]-[hash]-${timestamp}.js`; // Custom file name, use timestamp to ensure uniqueness          }
        },
        entryFileNames: ({ name }) => {
          if (name === 'vendor') {
            return `assets/js/[name]-[hash].js`; // Third-party libraries do not add timestamps          } else {
            return `assets/js/[name]-[hash]-${timestamp}.js`; // Custom file name, use timestamp to ensure uniqueness          }
        },
        assetFileNames: `assets/[ext]/[name]-[hash].[ext]` // Add a time stamp to the resource file      },
    }
  }
});

By settingchunkFileNamesandentryFileNamesFunction: Dynamically set the file name of the output file based on whether the file name is a third-party library. For third-party libraries, no timestamp is added to ensure that their file names are stable; for custom files, timestamps are used to ensure that the file names generated by each build are unique. This configuration can effectively avoid browser caching problems, ensure that the browser can load the latest code every time, without affecting the cache effect of third-party libraries.

Summarize

This is the article about how to use vite to solve the problem of browser caching after front-end distribution. For more related vite to solve the content of front-end browser caching, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!