1+ import path from 'path' ;
12import type { Plugin , ResolvedConfig } from 'vite' ;
23import { normalizePath } from 'vite' ;
34import {
@@ -7,17 +8,21 @@ import {
78 getSourceFromVirtualCssFile ,
89 compile ,
910 hash ,
11+ getPackageInfo ,
1012} from '@vanilla-extract/integration' ;
1113
1214export 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