Skip to content

Commit 4e92cce

Browse files
authored
vite: Add inlineCssInDev option to fix FOUC in SSR dev (#1614)
1 parent b733023 commit 4e92cce

File tree

5 files changed

+262
-141
lines changed

5 files changed

+262
-141
lines changed

.changeset/cyan-bikes-relax.md

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
---
2+
'@vanilla-extract/compiler': minor
3+
---
4+
5+
Add new `getAllCss` API
6+
7+
The `Compiler` class now provides a `getAllCss` method that returns all the CSS currently stored by the compiler.
8+
9+
**EXAMPLE USAGE**:
10+
11+
```ts
12+
import { createCompiler } from '@vanilla-extract/compiler';
13+
14+
const compiler = createCompiler({
15+
root: process.cwd(),
16+
});
17+
18+
await compiler.processVanillaFile('foo.css.ts');
19+
await compiler.processVanillaFile('bar.css.ts');
20+
21+
// Contains all CSS created by `foo.css.ts` and `bar.css.ts`
22+
const allCss = compiler.getAllCss();
23+
```

.changeset/shiny-emus-guess.md

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
---
2+
'@vanilla-extract/vite-plugin': minor
3+
---
4+
5+
Add new `inlineCssInDev` option to `unstable_mode` configuration property
6+
7+
Setting `unstableMode: 'inlineCssInDev'` will result in all CSS generated by Vanilla Extract being inlined into a `style` element at the top of the document `head`. This feature is useful for preventing [FOUC] (Flash of Unstyled Content) when server-rendering your initial HTML. Without this, calling `ssrLoadModule` on your server entrypoint will not include the CSS in the HTML, leading to a FOUC when the client-side JavaScript takes over.
8+
9+
Note that CSS will only be inlined in development mode. Production builds are unaffected by this setting.
10+
11+
**EXAMPLE USAGE**:
12+
13+
```ts
14+
// vite.config.ts
15+
import { vanillaExtractPlugin } from '@vanilla-extract/vite-plugin';
16+
17+
export default {
18+
plugins: [
19+
vanillaExtractPlugin({
20+
unstable_mode: 'inlineCssInDev',
21+
}),
22+
],
23+
}
24+
```
25+
26+
[FOUC]: https://en.wikipedia.org/wiki/Flash_of_unstyled_content

packages/compiler/src/compiler.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -240,6 +240,7 @@ export interface Compiler {
240240
): Promise<{ source: string; watchFiles: Set<string> }>;
241241
getCssForFile(virtualCssFilePath: string): { filePath: string; css: string };
242242
close(): Promise<void>;
243+
getAllCss(): string;
243244
}
244245

245246
interface ProcessedVanillaFile {
@@ -499,5 +500,16 @@ export const createCompiler = ({
499500

500501
await server.close();
501502
},
503+
getAllCss() {
504+
let allCss = '';
505+
506+
for (const { css } of cssCache.values()) {
507+
if (css) {
508+
allCss += css + '\n';
509+
}
510+
}
511+
512+
return allCss;
513+
},
502514
};
503515
};

0 commit comments

Comments
 (0)