-
Notifications
You must be signed in to change notification settings - Fork 4.5k
/
Copy pathindex.ts
354 lines (293 loc) · 10.6 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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
import { compile, env, Features, Instrumentation, normalizePath, optimize } from '@tailwindcss/node'
import { clearRequireCache } from '@tailwindcss/node/require-cache'
import { Scanner } from '@tailwindcss/oxide'
import fs from 'node:fs/promises'
import path from 'node:path'
import type { Plugin, ResolvedConfig, ViteDevServer } from 'vite'
const DEBUG = env.DEBUG
const SPECIAL_QUERY_RE = /[?&](?:worker|sharedworker|raw|url)\b/
const COMMON_JS_PROXY_RE = /\?commonjs-proxy/
const INLINE_STYLE_ID_RE = /[?&]index\=\d+\.css$/
export interface TailwindPluginOptions {
ignore?: (string | RegExp | ((id: string) => boolean))[]
}
export default function tailwindcss(pluginOptions?: TailwindPluginOptions): Plugin[] {
let servers: ViteDevServer[] = []
let config: ResolvedConfig | null = null
let ignoredFiles = pluginOptions?.ignore??[];
let isSSR = false
let minify = false
let roots: DefaultMap<string, Root> = new DefaultMap((id) => {
let cssResolver = config!.createResolver({
...config!.resolve,
extensions: ['.css'],
mainFields: ['style'],
conditions: ['style', 'development|production'],
tryIndex: false,
preferRelative: true,
})
function customCssResolver(id: string, base: string) {
return cssResolver(id, base, true, isSSR)
}
let jsResolver = config!.createResolver(config!.resolve)
function customJsResolver(id: string, base: string) {
return jsResolver(id, base, true, isSSR)
}
return new Root(id, config!.root, customCssResolver, customJsResolver)
})
return [
{
// Step 1: Scan source files for candidates
name: '@tailwindcss/vite:scan',
enforce: 'pre',
configureServer(server) {
servers.push(server)
},
async configResolved(_config) {
config = _config
minify = config.build.cssMinify !== false
isSSR = config.build.ssr !== false && config.build.ssr !== undefined
},
},
{
// Step 2 (serve mode): Generate CSS
name: '@tailwindcss/vite:generate:serve',
apply: 'serve',
enforce: 'pre',
async transform(src, id, options) {
if (!isPotentialCssRootFile(id, ignoredFiles)) return
using I = new Instrumentation()
DEBUG && I.start('[@tailwindcss/vite] Generate CSS (serve)')
let root = roots.get(id)
let generated = await root.generate(src, (file) => this.addWatchFile(file), I)
if (!generated) {
roots.delete(id)
return src
}
DEBUG && I.end('[@tailwindcss/vite] Generate CSS (serve)')
return { code: generated }
},
},
{
// Step 2 (full build): Generate CSS
name: '@tailwindcss/vite:generate:build',
apply: 'build',
enforce: 'pre',
async transform(src, id) {
if (!isPotentialCssRootFile(id, ignoredFiles)) return
using I = new Instrumentation()
DEBUG && I.start('[@tailwindcss/vite] Generate CSS (build)')
let root = roots.get(id)
let generated = await root.generate(src, (file) => this.addWatchFile(file), I)
if (!generated) {
roots.delete(id)
return src
}
DEBUG && I.end('[@tailwindcss/vite] Generate CSS (build)')
DEBUG && I.start('[@tailwindcss/vite] Optimize CSS')
generated = optimize(generated, { minify })
DEBUG && I.end('[@tailwindcss/vite] Optimize CSS')
return { code: generated }
},
},
] satisfies Plugin[]
}
function getExtension(id: string) {
let [filename] = id.split('?', 2)
return path.extname(filename).slice(1)
}
function isPotentialCssRootFile(id: string, ignoredFiles: Exclude<TailwindPluginOptions["ignore"], undefined>) {
if (id.includes('/.vite/')) return
let isIgnoredPattern = ignoredFiles.some(matcher => {
if(matcher instanceof RegExp){
return matcher.test(id);
}
if(matcher instanceof Function){
return matcher(id);
}
return matcher.includes(matcher)
});
// User defined ignore pattern
if(isIgnoredPattern) return
let extension = getExtension(id)
let isCssFile =
(extension === 'css' || id.includes('&lang.css') || id.match(INLINE_STYLE_ID_RE)) &&
// Don't intercept special static asset resources
!SPECIAL_QUERY_RE.test(id) &&
!COMMON_JS_PROXY_RE.test(id)
return isCssFile
}
function idToPath(id: string) {
return path.resolve(id.replace(/\?.*$/, ''))
}
/**
* A Map that can generate default values for keys that don't exist.
* Generated default values are added to the map to avoid recomputation.
*/
class DefaultMap<K, V> extends Map<K, V> {
constructor(private factory: (key: K, self: DefaultMap<K, V>) => V) {
super()
}
get(key: K): V {
let value = super.get(key)
if (value === undefined) {
value = this.factory(key, this)
this.set(key, value)
}
return value
}
}
class Root {
// The lazily-initialized Tailwind compiler components. These are persisted
// throughout rebuilds but will be re-initialized if the rebuild strategy is
// set to `full`.
private compiler?: Awaited<ReturnType<typeof compile>>
// The lazily-initialized Tailwind scanner.
private scanner?: Scanner
// List of all candidates that were being returned by the root scanner during
// the lifetime of the root.
private candidates: Set<string> = new Set<string>()
// List of all build dependencies (e.g. imported stylesheets or plugins) and
// their last modification timestamp. If no mtime can be found, we need to
// assume the file has always changed.
private buildDependencies = new Map<string, number | null>()
constructor(
private id: string,
private base: string,
private customCssResolver: (id: string, base: string) => Promise<string | false | undefined>,
private customJsResolver: (id: string, base: string) => Promise<string | false | undefined>,
) {}
// Generate the CSS for the root file. This can return false if the file is
// not considered a Tailwind root. When this happened, the root can be GCed.
public async generate(
content: string,
_addWatchFile: (file: string) => void,
I: Instrumentation,
): Promise<string | false> {
function addWatchFile(file: string) {
// Scanning `.svg` file containing a `#` or `?` in the path will
// crash Vite. We work around this for now by ignoring updates to them.
//
// https://github.com/tailwindlabs/tailwindcss/issues/16877
if (/[\#\?].*\.svg$/.test(file)) {
return
}
_addWatchFile(file)
}
let requiresBuildPromise = this.requiresBuild()
let inputPath = idToPath(this.id)
let inputBase = path.dirname(path.resolve(inputPath))
if (!this.compiler || !this.scanner || (await requiresBuildPromise)) {
clearRequireCache(Array.from(this.buildDependencies.keys()))
this.buildDependencies.clear()
this.addBuildDependency(idToPath(inputPath))
DEBUG && I.start('Setup compiler')
let addBuildDependenciesPromises: Promise<void>[] = []
this.compiler = await compile(content, {
base: inputBase,
shouldRewriteUrls: true,
onDependency: (path) => {
addWatchFile(path)
addBuildDependenciesPromises.push(this.addBuildDependency(path))
},
customCssResolver: this.customCssResolver,
customJsResolver: this.customJsResolver,
})
await Promise.all(addBuildDependenciesPromises)
DEBUG && I.end('Setup compiler')
DEBUG && I.start('Setup scanner')
let sources = (() => {
// Disable auto source detection
if (this.compiler.root === 'none') {
return []
}
// No root specified, auto-detect based on the `**/*` pattern
if (this.compiler.root === null) {
return [{ base: this.base, pattern: '**/*', negated: false }]
}
// Use the specified root
return [{ ...this.compiler.root, negated: false }]
})().concat(this.compiler.sources)
this.scanner = new Scanner({ sources })
DEBUG && I.end('Setup scanner')
} else {
for (let buildDependency of this.buildDependencies.keys()) {
addWatchFile(buildDependency)
}
}
if (
!(
this.compiler.features &
(Features.AtApply | Features.JsPluginCompat | Features.ThemeFunction | Features.Utilities)
)
) {
return false
}
if (this.compiler.features & Features.Utilities) {
// This should not be here, but right now the Vite plugin is setup where we
// setup a new scanner and compiler every time we request the CSS file
// (regardless whether it actually changed or not).
DEBUG && I.start('Scan for candidates')
for (let candidate of this.scanner.scan()) {
this.candidates.add(candidate)
}
DEBUG && I.end('Scan for candidates')
}
if (this.compiler.features & Features.Utilities) {
// Watch individual files found via custom `@source` paths
for (let file of this.scanner.files) {
addWatchFile(file)
}
// Watch globs found via custom `@source` paths
for (let glob of this.scanner.globs) {
if (glob.pattern[0] === '!') continue
let relative = path.relative(this.base, glob.base)
if (relative[0] !== '.') {
relative = './' + relative
}
// Ensure relative is a posix style path since we will merge it with the
// glob.
relative = normalizePath(relative)
addWatchFile(path.posix.join(relative, glob.pattern))
let root = this.compiler.root
if (root !== 'none' && root !== null) {
let basePath = normalizePath(path.resolve(root.base, root.pattern))
let isDir = await fs.stat(basePath).then(
(stats) => stats.isDirectory(),
() => false,
)
if (!isDir) {
throw new Error(
`The path given to \`source(…)\` must be a directory but got \`source(${basePath})\` instead.`,
)
}
}
}
}
DEBUG && I.start('Build CSS')
let result = this.compiler.build([...this.candidates])
DEBUG && I.end('Build CSS')
return result
}
private async addBuildDependency(path: string) {
let mtime: number | null = null
try {
mtime = (await fs.stat(path)).mtimeMs
} catch {}
this.buildDependencies.set(path, mtime)
}
private async requiresBuild(): Promise<boolean> {
for (let [path, mtime] of this.buildDependencies) {
if (mtime === null) return true
try {
let stat = await fs.stat(path)
if (stat.mtimeMs > mtime) {
return true
}
} catch {
return true
}
}
return false
}
}