Skip to content

Implement enableDevCache option in Vite plugin #1591

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/forty-clocks-leave.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@vanilla-extract/vite-plugin': minor
---

Implement an `enableDevCache` option in the Vite plugin which helps alleviate dev server performance issues in large projects caused by redundant `.vanilla.css` file loading
62 changes: 59 additions & 3 deletions packages/vite-plugin/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import path from 'path';

import fs from 'fs/promises';
import type {
Plugin,
ResolvedConfig,
Expand All @@ -16,6 +16,7 @@ import {
getPackageInfo,
transform,
normalizePath,
hash
} from '@vanilla-extract/integration';

const PLUGIN_NAME = 'vite-plugin-vanilla-extract';
Expand All @@ -41,6 +42,13 @@ type PluginFilter = (filterProps: {

interface Options {
identifiers?: IdentifierOption;
/**
* Enables hash-based (MD5) caching of `.css.ts` file contents in dev mode to avoid unnecessary module
* reloads. Helpful in large projects where the same `.css.ts` files (e.g. sprinkles) are imported
* in many places and we don't want the dev client to have to re-download them every time they're imported.
* @default false
*/
enableDevCache?: boolean;
unstable_pluginFilter?: PluginFilter;
unstable_mode?: 'transform' | 'emitCss';
}
Expand All @@ -59,6 +67,7 @@ const withUserPluginFilter =

export function vanillaExtractPlugin({
identifiers,
enableDevCache = false,
unstable_pluginFilter: pluginFilter = defaultPluginFilter,
unstable_mode: mode = 'emitCss',
}: Options = {}): Plugin {
Expand Down Expand Up @@ -91,14 +100,54 @@ export function vanillaExtractPlugin({
return normalizePath(resolvedId);
};

// Cache for file content hashes to avoid unnecessary invalidations
const fileContentHashes = new Map<string, string>();

// Helper to hash file contents
async function getFileHash(filePath: string): Promise<string | undefined> {
try {
const content = await fs.readFile(filePath, 'utf8');
return hash(content);
} catch {
console.warn('Unable to read file for hash calculation:', filePath);
// If file can't be read, treat as changed
return undefined;
}
}

// Helper to determine if a module should be invalidated based on dev cache
async function shouldInvalidateModule(moduleId: string): Promise<boolean> {
if (
!enableDevCache ||
!moduleId
) {
return true;
}

const hash = await getFileHash(moduleId);
Copy link
Author

@hartz89 hartz89 May 21, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is the hashing step just a waste of CPU time? Should we just use the file contents as the values of the map? Hashing CPU time is a trade-off for cache memory usage.


if (!hash) {
return true;
}

const prevHash = fileContentHashes.get(moduleId);

if (hash !== prevHash) {
fileContentHashes.set(moduleId, hash);
return true;
}

return false;
}

function invalidateModule(absoluteId: string) {
if (!server) return;

const { moduleGraph } = server;
const modules = moduleGraph.getModulesByFile(absoluteId);

if (modules) {
for (const module of modules) {
for (const module of modules) {
moduleGraph.invalidateModule(module);

// Vite uses this timestamp to add `?t=` query string automatically for HMR.
Expand Down Expand Up @@ -217,9 +266,10 @@ export function vanillaExtractPlugin({
}

for (const file of watchFiles) {
const normalizedFilePath = normalizePath(file);
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wasn't sure if I should put the invalidation check before or after the "add watch file" block, or how these blocks might affect one another. Let me know if you have thoughts.

if (
!file.includes('node_modules') &&
normalizePath(file) !== absoluteId
normalizedFilePath !== absoluteId
) {
this.addWatchFile(file);
}
Expand All @@ -228,6 +278,12 @@ export function vanillaExtractPlugin({
// The deps have to be invalidated in case one of them changing was the trigger causing
// the current transformation
if (cssFileFilter.test(file)) {
const shouldInvalidate = await shouldInvalidateModule(normalizedFilePath);

if (!shouldInvalidate) {
continue;
}

invalidateModule(fileIdToVirtualId(file));
}
}
Expand Down
20 changes: 20 additions & 0 deletions site/docs/integrations/vite.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,3 +60,23 @@ vanillaExtractPlugin({
```

Each integration will set a default value based on the configuration options passed to the bundler.

### enableDevCache

This option can help mitigate dev mode [performance issues](https://github.com/vanilla-extract-css/vanilla-extract/issues/1488) in large projects, especially those using `sprinkles` or other common `.css.ts` imports. It ensures that `.vanilla.css` virtual files are only invalidated and re-fetched when their contents have actually change. This is accomplished by creating a map of `.css.ts` file paths to MD5 hashes of their content.

The trade-offs for this option include more filesystem operations and potentially higher memory usage in the plugin.

```js
// vite.config.js

import { vanillaExtractPlugin } from '@vanilla-extract/vite-plugin';

export default {
plugins: [
vanillaExtractPlugin({
enableDevCache: true
})
]
};
```