DEV Community

Rafał Goławski
Rafał Goławski

Posted on

Avoiding File Hashing in Vite #️⃣

When building projects with Vite, you may encounter situations where you need to prevent certain files from being hashed during the build process. This can be particularly useful when working with assets that need consistent naming, such background.js file while working with Chrome extensions.

To achieve this, you can modify your vite.config.js file to customize the output filenames. Here's a simple approach:

import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import { resolve } from "path";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()], // Optional, depends on library that you use
  build: {
    rollupOptions: {
      input: {
        // Define entry points for the build
        main: resolve(__dirname, "index.html"),
        background: resolve(__dirname, "src/background.ts"),
        content: resolve(__dirname, "src/content.ts"),
      },
      output: {
        entryFileNames: (chunkInfo) => {
          // Filenames you want to keep unhashed
          const noHashFiles = ["background", "content"];
          if (noHashFiles.includes(chunkInfo.name)) {
            return "[name].js"; // Keep file unhashed
          }
          return "assets/[name]-[hash].js"; // Hash other entry files
        },
        // Naming patterns for various output file types
        chunkFileNames: "assets/[name]-[hash].js",
        assetFileNames: "assets/[name]-[hash].[ext]",
      },
    },
  },
});
Enter fullscreen mode Exit fullscreen mode

In this configuration, we're using the rollupOptions to specify custom output patterns. The entryFileNames function checks for specific file names (in this case, 'background') and returns a non-hashed filename for those. All other files will still use the default hashing pattern.

Hope you find this useful. Thanks for reading! 👋

Top comments (3)

Collapse
 
mikhail_akulov_49314fc689 profile image
Mikhail Akulov

But this effectively turns off the cache busting for these files, so "background" and "content" will be taken from old browser cache when they are updated, aren't they?

Collapse
 
rgolawski profile image
Rafał Goławski

Well, technically yes - turning off hashing does remove the cache-busting mechanism. But in the context of a Chrome extension, that's not really a problem, because all chrome://extensions assets are loaded from the extension package on disk. When a user installs an update, Chrome replaces the entire bundle at once, so stale background.js or content.js scripts are never served.

Collapse
 
mikhail_akulov_49314fc689 profile image
Mikhail Akulov

If browser caching is not an issue, you could just remove [hash] tags altogether