-
Notifications
You must be signed in to change notification settings - Fork 296
/
index.ts
254 lines (216 loc) · 6.87 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
import path from 'path';
import type { Plugin, ResolvedConfig, ViteDevServer } from 'vite';
import { normalizePath } from 'vite';
import outdent from 'outdent';
import {
cssFileFilter,
processVanillaFile,
compile,
IdentifierOption,
getPackageInfo,
CompileOptions,
transform,
} from '@vanilla-extract/integration';
import { PostCSSConfigResult, resolvePostcssConfig } from './postcss';
const styleUpdateEvent = (fileId: string) =>
`vanilla-extract-style-update:${fileId}`;
const virtualExtCss = '.vanilla.css';
const virtualExtJs = '.vanilla.js';
interface Options {
identifiers?: IdentifierOption;
emitCssInSsr?: boolean;
esbuildOptions?: CompileOptions['esbuildOptions'];
}
export function vanillaExtractPlugin({
identifiers,
emitCssInSsr,
esbuildOptions,
}: Options = {}): Plugin {
let config: ResolvedConfig;
let server: ViteDevServer;
let postCssConfig: PostCSSConfigResult | null;
const cssMap = new Map<string, string>();
const hasEmitCssOverride = typeof emitCssInSsr === 'boolean';
let resolvedEmitCssInSsr: boolean = hasEmitCssOverride
? emitCssInSsr
: !!process.env.VITE_RSC_BUILD;
let packageName: string;
const getAbsoluteVirtualFileId = (source: string) =>
normalizePath(path.join(config.root, source));
return {
name: 'vanilla-extract',
enforce: 'pre',
configureServer(_server) {
server = _server;
},
config(_userConfig, env) {
const include =
env.command === 'serve' ? ['@vanilla-extract/css/injectStyles'] : [];
return {
optimizeDeps: { include },
ssr: {
external: [
'@vanilla-extract/css',
'@vanilla-extract/css/fileScope',
'@vanilla-extract/css/adapter',
],
},
};
},
async configResolved(resolvedConfig) {
config = resolvedConfig;
packageName = getPackageInfo(config.root).name;
if (config.command === 'serve') {
postCssConfig = await resolvePostcssConfig(config);
}
if (
!hasEmitCssOverride &&
config.plugins.some((plugin) =>
[
'astro:build',
'solid-start-server',
'vite-plugin-qwik',
'vite-plugin-svelte',
].includes(plugin.name),
)
) {
resolvedEmitCssInSsr = true;
}
},
resolveId(source) {
const [validId, query] = source.split('?');
if (!validId.endsWith(virtualExtCss) && !validId.endsWith(virtualExtJs)) {
return;
}
// Absolute paths seem to occur often in monorepos, where files are
// imported from outside the config root.
const absoluteId = source.startsWith(config.root)
? source
: getAbsoluteVirtualFileId(validId);
// There should always be an entry in the `cssMap` here.
// The only valid scenario for a missing one is if someone had written
// a file in their app using the .vanilla.js/.vanilla.css extension
if (cssMap.has(absoluteId)) {
// Keep the original query string for HMR.
return absoluteId + (query ? `?${query}` : '');
}
},
load(id) {
const [validId] = id.split('?');
if (!cssMap.has(validId)) {
return;
}
const css = cssMap.get(validId);
if (typeof css !== 'string') {
return;
}
if (validId.endsWith(virtualExtCss)) {
return css;
}
return outdent`
import { injectStyles } from '@vanilla-extract/css/injectStyles';
const inject = (css) => injectStyles({
fileScope: ${JSON.stringify({ filePath: validId })},
css
});
inject(${JSON.stringify(css)});
if (import.meta.hot) {
import.meta.hot.on('${styleUpdateEvent(validId)}', (css) => {
inject(css);
});
}
`;
},
async transform(code, id, ssrParam) {
const [validId] = id.split('?');
if (!cssFileFilter.test(validId)) {
return null;
}
const identOption =
identifiers ?? (config.mode === 'production' ? 'short' : 'debug');
let ssr: boolean | undefined;
if (typeof ssrParam === 'boolean') {
ssr = ssrParam;
} else {
ssr = ssrParam?.ssr;
}
if (ssr && !resolvedEmitCssInSsr) {
return transform({
source: code,
filePath: normalizePath(validId),
rootPath: config.root,
packageName,
identOption,
});
}
const { source, watchFiles } = await compile({
filePath: validId,
cwd: config.root,
esbuildOptions,
identOption,
});
for (const file of watchFiles) {
// In start mode, we need to prevent the file from rewatching itself.
// If it's a `build --watch`, it needs to watch everything.
if (config.command === 'build' || normalizePath(file) !== validId) {
this.addWatchFile(file);
}
}
const output = await processVanillaFile({
source,
filePath: validId,
identOption,
serializeVirtualCssPath: async ({ fileScope, source }) => {
const rootRelativeId = `${fileScope.filePath}${
config.command === 'build' || (ssr && resolvedEmitCssInSsr)
? virtualExtCss
: virtualExtJs
}`;
const absoluteId = getAbsoluteVirtualFileId(rootRelativeId);
let cssSource = source;
if (postCssConfig) {
const postCssResult = await (await import('postcss'))
.default(postCssConfig.plugins)
.process(source, {
...postCssConfig.options,
from: undefined,
map: false,
});
cssSource = postCssResult.css;
}
if (
server &&
cssMap.has(absoluteId) &&
cssMap.get(absoluteId) !== source
) {
const { moduleGraph } = server;
const modules = Array.from(
moduleGraph.getModulesByFile(absoluteId) || [],
);
for (const module of modules) {
if (module) {
moduleGraph.invalidateModule(module);
// Vite uses this timestamp to add `?t=` query string automatically for HMR.
module.lastHMRTimestamp =
(module as any).lastInvalidationTimestamp || Date.now();
}
}
server.ws.send({
type: 'custom',
event: styleUpdateEvent(absoluteId),
data: cssSource,
});
}
cssMap.set(absoluteId, cssSource);
// We use the root relative id here to ensure file contents (content-hashes)
// are consistent across build machines
return `import "${rootRelativeId}";`;
},
});
return {
code: output,
map: { mappings: '' },
};
},
};
}