Change JS, CSS, and other asset filenames during build in vite

By default, the build command in vite always changes the CSS and JS filenames.

To have a unique JS and CSS filenames, the following build code can be added in vite.config.ts file.

build: {
    outDir: "dist",
    emptyOutDir: true,
    minify: true,
    assetsDir: "assets",
    cssCodeSplit: false,
    sourcemap: false,
    ssr: false,
    rollupOptions: {
      treeshake: true,
      output: {
        entryFileNames: `assets/custom.min.js`,
        chunkFileNames: `assets/index-chunk.js`,
        // assetFileNames: `assets/[name].[ext]`,
        assetFileNames: (assetInfo) => {
          if (assetInfo.name === "style.css") return `assets/custom.min.css`;
          return `assets/${assetInfo.name}`;
        },
      },
    },
  },

We can also have assetFileNames: `assets/[name].[ext]`. But with this code, the CSS file name is going to be style.css. To update it further, we are using the assetFileNames value as a function to have more control.

Below is the complete code:

vite.config.ts

export default defineConfig({
  plugins: [react()],
  resolve: {
    alias: [
      {
        find: "@",
        replacement: fileURLToPath(new URL("./src", import.meta.url)),
      },
      {
        find: "@components",
        replacement: fileURLToPath(
          new URL("./src/components", import.meta.url)
        ),
      },
  },
  build: {
    outDir: "dist",
    emptyOutDir: true,
    minify: true,
    assetsDir: "assets",
    cssCodeSplit: false,
    sourcemap: false,
    ssr: false,
    rollupOptions: {
      treeshake: true,
      output: {
        entryFileNames: `assets/custom.min.js`,
        chunkFileNames: `assets/index-chunk.js`,
        // assetFileNames: `assets/[name].[ext]`,
        assetFileNames: (assetInfo) => {
          if (assetInfo.name === "style.css") return `assets/custom.min.css`;
          return `assets/${assetInfo.name}`;
        },
      },
    },
  },
});