Skip to content

Commit 416eb9a

Browse files
authored
Vite: Add runtime evaluation of vanilla-extract files for SSR (#311)
1 parent 15cff71 commit 416eb9a

File tree

2 files changed

+43
-15
lines changed

2 files changed

+43
-15
lines changed

.changeset/tidy-geckos-act.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
---
2+
'@vanilla-extract/vite-plugin': minor
3+
---
4+
5+
In SSR mode, move to runtime evaluation of vanilla-extract files
6+
7+
This unlocks the potential for CSS extraction on the server.

packages/vite-plugin/src/index.ts

Lines changed: 36 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import path from 'path';
12
import type { Plugin, ResolvedConfig } from 'vite';
23
import { normalizePath } from 'vite';
34
import {
@@ -7,17 +8,21 @@ import {
78
getSourceFromVirtualCssFile,
89
compile,
910
hash,
11+
getPackageInfo,
1012
} from '@vanilla-extract/integration';
1113

1214
export function vanillaExtractPlugin(): Plugin {
1315
let config: ResolvedConfig;
16+
let packageInfo: ReturnType<typeof getPackageInfo>;
1417
const cssMap = new Map<string, string>();
1518

1619
return {
1720
name: 'vanilla-extract',
1821
enforce: 'pre',
1922
configResolved(resolvedConfig) {
2023
config = resolvedConfig;
24+
25+
packageInfo = getPackageInfo(config.root);
2126
},
2227
resolveId(id) {
2328
if (virtualCssFileFilter.test(id)) {
@@ -44,25 +49,41 @@ export function vanillaExtractPlugin(): Plugin {
4449

4550
return null;
4651
},
47-
async transform(_code, id, ssr) {
48-
if (cssFileFilter.test(id)) {
49-
const { source, watchFiles } = await compile({
50-
filePath: id,
51-
cwd: config.root,
52-
});
52+
async transform(code, id, ssr) {
53+
if (!cssFileFilter.test(id)) {
54+
return null;
55+
}
5356

54-
for (const file of watchFiles) {
55-
this.addWatchFile(file);
56-
}
57+
if (ssr && code.indexOf('@vanilla-extract/css/fileScope') === -1) {
58+
const filePath = normalizePath(path.relative(packageInfo.dirname, id));
5759

58-
return processVanillaFile({
59-
source,
60-
filePath: id,
61-
outputCss: !ssr,
62-
});
60+
const packageName = packageInfo.name
61+
? `"${packageInfo.name}"`
62+
: 'undefined';
63+
64+
return `
65+
import { setFileScope, endFileScope } from "@vanilla-extract/css/fileScope";
66+
setFileScope("${filePath}", ${packageName});
67+
68+
${code}
69+
endFileScope();
70+
`;
6371
}
6472

65-
return null;
73+
const { source, watchFiles } = await compile({
74+
filePath: id,
75+
cwd: config.root,
76+
});
77+
78+
for (const file of watchFiles) {
79+
this.addWatchFile(file);
80+
}
81+
82+
return processVanillaFile({
83+
source,
84+
filePath: id,
85+
outputCss: !ssr,
86+
});
6687
},
6788
};
6889
}

0 commit comments

Comments
 (0)