-
Notifications
You must be signed in to change notification settings - Fork 297
/
index.ts
68 lines (58 loc) · 1.62 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import type { Plugin, ResolvedConfig } from 'vite';
import { normalizePath } from 'vite';
import {
cssFileFilter,
virtualCssFileFilter,
processVanillaFile,
getSourceFromVirtualCssFile,
compile,
hash,
} from '@vanilla-extract/integration';
export function vanillaExtractPlugin(): Plugin {
let config: ResolvedConfig;
const cssMap = new Map<string, string>();
return {
name: 'vanilla-extract',
enforce: 'pre',
configResolved(resolvedConfig) {
config = resolvedConfig;
},
resolveId(id) {
if (virtualCssFileFilter.test(id)) {
const { fileName, source } = getSourceFromVirtualCssFile(id);
// resolveId shouldn't really cause a side-effect however custom module meta isn't currently working
// This is a hack work around until https://github.com/vitejs/vite/issues/3240 is resolved
const shortHashFileName = normalizePath(
`${fileName}?hash=${hash(source)}`,
);
cssMap.set(shortHashFileName, source);
return shortHashFileName;
}
},
load(id) {
if (cssMap.has(id)) {
const css = cssMap.get(id);
cssMap.delete(id);
return css;
}
return null;
},
async transform(_code, id, ssr) {
if (cssFileFilter.test(id)) {
const { source, watchFiles } = await compile({
filePath: id,
cwd: config.root,
});
for (const file of watchFiles) {
this.addWatchFile(file);
}
return processVanillaFile({
source,
filePath: id,
outputCss: !ssr,
});
}
return null;
},
};
}