This repository was archived by the owner on Mar 19, 2026. It is now read-only.
forked from vitejs/vite
-
-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathcss.ts
More file actions
3532 lines (3233 loc) · 107 KB
/
css.ts
File metadata and controls
3532 lines (3233 loc) · 107 KB
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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import fs from 'node:fs'
import fsp from 'node:fs/promises'
import path from 'node:path'
import { fileURLToPath, pathToFileURL } from 'node:url'
import postcssrc from 'postcss-load-config'
import type {
ExistingRawSourceMap,
InternalModuleFormat,
OutputAsset,
OutputChunk,
RenderedChunk,
RenderedModule,
RollupError,
SourceMapInput,
} from 'rolldown'
import { dataToEsm } from '@rollup/pluginutils'
import colors from 'picocolors'
import MagicString from 'magic-string'
import type * as PostCSS from 'postcss'
import type Sass from 'sass'
import type Stylus from 'stylus'
import type Less from 'less'
import type { RawSourceMap } from '@jridgewell/remapping'
import { WorkerWithFallback } from 'artichokie'
import { globSync } from 'tinyglobby'
import type {
TransformAttributeResult as LightningCssTransformAttributeResult,
TransformResult as LightningCssTransformResult,
} from 'lightningcss'
import { viteCSSPlugin, viteCSSPostPlugin } from 'rolldown/experimental'
import type { LightningCSSOptions } from '#types/internal/lightningcssOptions'
import type {
LessPreprocessorBaseOptions,
SassModernPreprocessBaseOptions,
StylusPreprocessorBaseOptions,
} from '#types/internal/cssPreprocessorOptions'
import type { EsbuildTransformOptions } from '#types/internal/esbuildOptions'
import type { CustomPluginOptionsVite } from '#types/metadata'
import { getCodeWithSourcemap, injectSourcesContent } from '../server/sourcemap'
import type { EnvironmentModuleNode } from '../server/moduleGraph'
import {
createToImportMetaURLBasedRelativeRuntime,
resolveUserExternal,
toOutputFilePathInCss,
toOutputFilePathInJS,
} from '../build'
import type { LibraryOptions } from '../build'
import {
CLIENT_PUBLIC_PATH,
CSS_LANGS_RE,
DEV_PROD_CONDITION,
ESBUILD_BASELINE_WIDELY_AVAILABLE_TARGET,
SPECIAL_QUERY_RE,
} from '../constants'
import type { ResolvedConfig } from '../config'
import type { Plugin } from '../plugin'
import { checkPublicFile } from '../publicDir'
import {
_dirname,
arraify,
asyncReplace,
combineSourcemaps,
createSerialPromiseQueue,
emptyCssComments,
encodeURIPath,
escapeRegex,
generateCodeFrame,
getHash,
getPackageManagerCommand,
getPkgName,
injectQuery,
isCSSRequest,
isDataUrl,
isExternalUrl,
isObject,
joinUrlSegments,
mergeWithDefaults,
normalizePath,
processSrcSet,
removeDirectQuery,
removeUrlQuery,
stripBomTag,
urlRE,
} from '../utils'
import type { Logger } from '../logger'
import { cleanUrl, isWindows, slash } from '../../shared/utils'
import { NULL_BYTE_PLACEHOLDER } from '../../shared/constants'
import { createBackCompatIdResolver } from '../idResolver'
import type { ResolveIdFn } from '../idResolver'
import { PartialEnvironment } from '../baseEnvironment'
import type { TransformPluginContext } from '../server/pluginContainer'
import { searchForWorkspaceRoot } from '../server/searchRoot'
import { type DevEnvironment, perEnvironmentPlugin } from '..'
import type { PackageCache } from '../packages'
import { findNearestMainPackageData } from '../packages'
import { nodeResolveWithVite } from '../nodeResolve'
import { addToHTMLProxyTransformResult } from './html'
import {
assetUrlRE,
cssEntriesMap,
fileToUrl,
publicAssetUrlCache,
publicAssetUrlRE,
publicFileToBuiltUrl,
renderAssetUrlInJS,
} from './asset'
import type { ESBuildOptions } from './esbuild'
import { getChunkOriginalFileName } from './manifest'
import { IIFE_BEGIN_RE, UMD_BEGIN_RE } from './oxc'
const decoder = new TextDecoder()
// const debug = createDebugger('vite:css')
export interface CSSOptions {
/**
* Using lightningcss is an experimental option to handle CSS modules,
* assets and imports via Lightning CSS. It requires to install it as a
* peer dependency.
*
* @default 'postcss'
* @experimental
*/
transformer?: 'postcss' | 'lightningcss'
/**
* https://github.com/css-modules/postcss-modules
*/
modules?: CSSModulesOptions | false
/**
* Options for preprocessors.
*
* In addition to options specific to each processors, Vite supports `additionalData` option.
* The `additionalData` option can be used to inject extra code for each style content.
*/
preprocessorOptions?: {
scss?: SassPreprocessorOptions
sass?: SassPreprocessorOptions
less?: LessPreprocessorOptions
styl?: StylusPreprocessorOptions
stylus?: StylusPreprocessorOptions
}
/**
* If this option is set, preprocessors will run in workers when possible.
* `true` means the number of CPUs minus 1.
*
* @default true
*/
preprocessorMaxWorkers?: number | true
postcss?:
| string
| (PostCSS.ProcessOptions & {
plugins?: PostCSS.AcceptedPlugin[]
})
/**
* Enables css sourcemaps during dev
* @default false
* @experimental
*/
devSourcemap?: boolean
/**
* @experimental
*/
lightningcss?: LightningCSSOptions
}
export interface CSSModulesOptions {
getJSON?: (
cssFileName: string,
json: Record<string, string>,
outputFileName: string,
) => void
scopeBehaviour?: 'global' | 'local'
globalModulePaths?: RegExp[]
exportGlobals?: boolean
generateScopedName?:
| string
| ((name: string, filename: string, css: string) => string)
hashPrefix?: string
/**
* default: undefined
*/
localsConvention?:
| 'camelCase'
| 'camelCaseOnly'
| 'dashes'
| 'dashesOnly'
| ((
originalClassName: string,
generatedClassName: string,
inputFile: string,
) => string)
}
const _cssConfigDefaults = Object.freeze({
/** @experimental */
transformer: 'postcss',
// modules
// preprocessorOptions
preprocessorMaxWorkers: true,
// postcss
/** @experimental */
devSourcemap: false,
// lightningcss
} satisfies CSSOptions)
export const cssConfigDefaults: Readonly<Partial<CSSOptions>> =
_cssConfigDefaults
export type ResolvedCSSOptions = Omit<CSSOptions, 'lightningcss'> &
Required<Pick<CSSOptions, 'transformer' | 'devSourcemap'>> & {
lightningcss?: LightningCSSOptions
}
export function resolveCSSOptions(
options: CSSOptions | undefined,
): ResolvedCSSOptions {
const resolved = mergeWithDefaults(_cssConfigDefaults, options ?? {})
if (resolved.transformer === 'lightningcss') {
resolved.lightningcss ??= {}
resolved.lightningcss.targets ??= convertTargets(
ESBUILD_BASELINE_WIDELY_AVAILABLE_TARGET,
)
}
return resolved
}
const cssModuleRE = new RegExp(`\\.module${CSS_LANGS_RE.source}`)
const directRequestRE = /[?&]direct\b/
const htmlProxyRE = /[?&]html-proxy\b/
const htmlProxyIndexRE = /&index=(\d+)/
const commonjsProxyRE = /[?&]commonjs-proxy/
const inlineRE = /[?&]inline\b/
const inlineCSSRE = /[?&]inline-css\b/
const styleAttrRE = /[?&]style-attr\b/
const functionCallRE = /^[A-Z_][.\w-]*\(/i
const transformOnlyRE = /[?&]transform-only\b/
const nonEscapedDoubleQuoteRe = /(?<!\\)"/g
const defaultCssBundleName = 'style.css'
const enum PreprocessLang {
less = 'less',
sass = 'sass',
scss = 'scss',
styl = 'styl',
stylus = 'stylus',
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars -- bug in typescript-eslint
const enum PureCssLang {
css = 'css',
}
const enum PostCssDialectLang {
sss = 'sugarss',
}
type CssLang =
| keyof typeof PureCssLang
| keyof typeof PreprocessLang
| keyof typeof PostCssDialectLang
export const isModuleCSSRequest = (request: string): boolean =>
cssModuleRE.test(request)
export const isDirectCSSRequest = (request: string): boolean =>
CSS_LANGS_RE.test(request) && directRequestRE.test(request)
export const isDirectRequest = (request: string): boolean =>
directRequestRE.test(request)
const cssModulesCache = new WeakMap<
ResolvedConfig,
Map<string, Record<string, string>>
>()
export const removedPureCssFilesCache: WeakMap<
ResolvedConfig,
Map<string, RenderedChunk>
> = new WeakMap()
// Used only if the config doesn't code-split CSS (builds a single CSS file)
export const cssBundleNameCache: WeakMap<ResolvedConfig, string> = new WeakMap()
const postcssConfigCache = new WeakMap<
ResolvedConfig,
PostCSSConfigResult | null | Promise<PostCSSConfigResult | null>
>()
function encodePublicUrlsInCSS(config: ResolvedConfig) {
return config.command === 'build'
}
const cssUrlAssetRE = /__VITE_CSS_URL__([\da-f]+)__/g
/**
* Plugin applied before user plugins
*/
export function cssPlugin(config: ResolvedConfig): Plugin {
const isBuild = config.command === 'build'
let moduleCache: Map<string, Record<string, string>>
const idResolver = createBackCompatIdResolver(config, {
preferRelative: true,
tryIndex: false,
extensions: [],
})
let preprocessorWorkerController: PreprocessorWorkerController | undefined
// warm up cache for resolved postcss config
if (config.css.transformer !== 'lightningcss') {
resolvePostcssConfig(config).catch(() => {
/* will be handled later */
})
}
if (isBuild && config.nativePluginEnabledLevel >= 2) {
return perEnvironmentPlugin('vite:native-css', (env) => {
return [
{
name: 'vite:css-compat',
buildStart() {
preprocessorWorkerController = createPreprocessorWorkerController(
normalizeMaxWorkers(config.css.preprocessorMaxWorkers),
)
preprocessorWorkerControllerCache.set(
config,
preprocessorWorkerController,
)
},
buildEnd() {
preprocessorWorkerController?.close()
},
},
viteCSSPlugin({
root: env.config.root,
isLib: !!env.config.build.lib,
publicDir: env.config.publicDir,
async compileCSS(url, importer, resolver) {
return compileCSS(
env,
url,
importer,
preprocessorWorkerController!,
(url, importer) => {
return resolver.call(url, importer)
},
)
},
resolveUrl(url, importer) {
return idResolver(env, url, importer)
},
assetInlineLimit: env.config.build.assetsInlineLimit,
}),
]
})
}
return {
name: 'vite:css',
buildStart() {
// Ensure a new cache for every build (i.e. rebuilding in watch mode)
moduleCache = new Map<string, Record<string, string>>()
cssModulesCache.set(config, moduleCache)
removedPureCssFilesCache.set(config, new Map<string, RenderedChunk>())
preprocessorWorkerController = createPreprocessorWorkerController(
normalizeMaxWorkers(config.css.preprocessorMaxWorkers),
)
preprocessorWorkerControllerCache.set(
config,
preprocessorWorkerController,
)
},
buildEnd() {
preprocessorWorkerController?.close()
},
load: {
filter: {
id: CSS_LANGS_RE,
},
async handler(id) {
if (urlRE.test(id)) {
if (isModuleCSSRequest(id)) {
throw new Error(
`?url is not supported with CSS modules. (tried to import ${JSON.stringify(
id,
)})`,
)
}
// *.css?url
// in dev, it's handled by assets plugin.
if (isBuild) {
id = injectQuery(removeUrlQuery(id), 'transform-only')
return (
`import ${JSON.stringify(id)};` +
`export default "__VITE_CSS_URL__${Buffer.from(id).toString(
'hex',
)}__"`
)
}
}
},
},
transform: {
filter: {
id: {
include: CSS_LANGS_RE,
exclude: [commonjsProxyRE, SPECIAL_QUERY_RE],
},
},
async handler(raw, id) {
const { environment } = this
const resolveUrl = (url: string, importer?: string) =>
idResolver(environment, url, importer)
const urlResolver: CssUrlResolver = async (url, importer) => {
const decodedUrl = decodeURI(url)
if (checkPublicFile(decodedUrl, config)) {
if (encodePublicUrlsInCSS(config)) {
return [publicFileToBuiltUrl(decodedUrl, config), undefined]
} else {
return [joinUrlSegments(config.base, decodedUrl), undefined]
}
}
const [id, fragment] = decodedUrl.split('#')
let resolved = await resolveUrl(id, importer)
if (resolved) {
if (fragment) resolved += '#' + fragment
let url = await fileToUrl(this, resolved)
// Inherit HMR timestamp if this asset was invalidated
if (!url.startsWith('data:') && this.environment.mode === 'dev') {
const mod = [
...(this.environment.moduleGraph.getModulesByFile(resolved) ??
[]),
].find((mod) => mod.type === 'asset')
if (mod?.lastHMRTimestamp) {
url = injectQuery(url, `t=${mod.lastHMRTimestamp}`)
}
}
return [url, resolved]
}
if (config.command === 'build') {
const isExternal = config.build.rollupOptions.external
? resolveUserExternal(
config.build.rollupOptions.external,
decodedUrl, // use URL as id since id could not be resolved
id,
false,
)
: false
if (!isExternal) {
// #9800 If we cannot resolve the css url, leave a warning.
config.logger.warnOnce(
`\n${decodedUrl} referenced in ${id} didn't resolve at build time, it will remain unchanged to be resolved at runtime`,
)
}
}
return [url, undefined]
}
const {
code: css,
modules,
deps,
map,
} = await compileCSS(
environment,
id,
raw,
preprocessorWorkerController!,
urlResolver,
)
if (modules) {
moduleCache.set(id, modules)
}
if (deps) {
for (const file of deps) {
this.addWatchFile(file)
}
}
return {
code: css,
map,
}
},
},
}
}
/**
* Plugin applied after user plugins
*/
export function cssPostPlugin(config: ResolvedConfig): Plugin {
// styles initialization in buildStart causes a styling loss in watch
const styles = new Map<string, string>()
// queue to emit css serially to guarantee the files are emitted in a deterministic order
let codeSplitEmitQueue = createSerialPromiseQueue<string>()
const urlEmitQueue = createSerialPromiseQueue<unknown>()
let pureCssChunks: Set<RenderedChunk>
// when there are multiple rollup outputs and extracting CSS, only emit once,
// since output formats have no effect on the generated CSS.
let hasEmitted = false
let chunkCSSMap: Map<string, string>
const rollupOptionsOutput = config.build.rollupOptions.output
const assetFileNames = (
Array.isArray(rollupOptionsOutput)
? rollupOptionsOutput[0]
: rollupOptionsOutput
)?.assetFileNames
const getCssAssetDirname = (cssAssetName: string) => {
const cssAssetNameDir = path.dirname(cssAssetName)
if (!assetFileNames) {
return path.join(config.build.assetsDir, cssAssetNameDir)
} else if (typeof assetFileNames === 'string') {
return path.join(path.dirname(assetFileNames), cssAssetNameDir)
} else {
return path.dirname(
assetFileNames({
type: 'asset',
names: [cssAssetName],
originalFileNames: [],
source: '/* vite internal call, ignore */',
}),
)
}
}
function getCssBundleName() {
const cached = cssBundleNameCache.get(config)
if (cached) return cached
const cssBundleName = config.build.lib
? resolveLibCssFilename(
config.build.lib,
config.root,
config.packageCache,
)
: defaultCssBundleName
cssBundleNameCache.set(config, cssBundleName)
return cssBundleName
}
if (config.command === 'build' && config.nativePluginEnabledLevel >= 2) {
return perEnvironmentPlugin('native:css-post', (env) => {
let libCssFilename: string | undefined
if (env.config.build.lib) {
const libOptions = env.config.build.lib
if (typeof libOptions.cssFileName === 'string') {
libCssFilename = `${libOptions.cssFileName}.css`
} else if (typeof libOptions.fileName === 'string') {
libCssFilename = `${libOptions.fileName}.css`
}
}
return [
viteCSSPostPlugin({
root: env.config.root,
isLib: !!env.config.build.lib,
isSsr: !!env.config.build.ssr,
isWorker: env.config.isWorker,
isClient: env.config.consumer === 'client',
cssCodeSplit: env.config.build.cssCodeSplit,
sourcemap: !!env.config.build.sourcemap,
assetsDir: env.config.build.assetsDir,
urlBase: env.config.base,
decodedBase: env.config.decodedBase,
libCssFilename,
cssMinify: env.config.build.cssMinify
? async (content, inline) => {
return await minifyCSS(content, env.config, inline)
}
: undefined,
renderBuiltUrl: env.config.experimental.renderBuiltUrl,
isOutputOptionsForLegacyChunks:
env.config.isOutputOptionsForLegacyChunks,
}),
]
})
}
return {
name: 'vite:css-post',
renderStart() {
// Ensure new caches for every build (i.e. rebuilding in watch mode)
pureCssChunks = new Set<RenderedChunk>()
hasEmitted = false
chunkCSSMap = new Map()
codeSplitEmitQueue = createSerialPromiseQueue()
},
transform: {
filter: {
id: {
include: CSS_LANGS_RE,
exclude: [commonjsProxyRE, SPECIAL_QUERY_RE],
},
},
async handler(css, id) {
css = stripBomTag(css)
// cache css compile result to map
// and then use the cache replace inline-style-flag
// when `generateBundle` in vite:build-html plugin and devHtmlHook
const inlineCSS = inlineCSSRE.test(id)
const isHTMLProxy = htmlProxyRE.test(id)
if (inlineCSS && isHTMLProxy) {
if (styleAttrRE.test(id)) {
css = css.replace(/"/g, '"')
}
const index = htmlProxyIndexRE.exec(id)?.[1]
if (index == null) {
throw new Error(`HTML proxy index in "${id}" not found`)
}
addToHTMLProxyTransformResult(
`${getHash(cleanUrl(id))}_${Number.parseInt(index)}`,
css,
)
return `export default ''`
}
const inlined = inlineRE.test(id)
const modules = cssModulesCache.get(config)!.get(id)
// #6984, #7552
// `foo.module.css` => modulesCode
// `foo.module.css?inline` => cssContent
const modulesCode =
modules &&
!inlined &&
dataToEsm(modules, { namedExports: true, preferConst: true })
if (config.command === 'serve') {
const getContentWithSourcemap = async (content: string) => {
if (config.css.devSourcemap) {
const sourcemap = this.getCombinedSourcemap()
if (sourcemap.mappings) {
await injectSourcesContent(
sourcemap,
cleanUrl(id),
config.logger,
)
}
return getCodeWithSourcemap('css', content, sourcemap)
}
return content
}
if (isDirectCSSRequest(id)) {
return null
}
if (inlined) {
return `export default ${JSON.stringify(css)}`
}
if (this.environment.config.consumer === 'server') {
return modulesCode || 'export {}'
}
const cssContent = await getContentWithSourcemap(css)
const code = [
`import { updateStyle as __vite__updateStyle, removeStyle as __vite__removeStyle } from ${JSON.stringify(
path.posix.join(config.base, CLIENT_PUBLIC_PATH),
)}`,
`const __vite__id = ${JSON.stringify(id)}`,
`const __vite__css = ${JSON.stringify(cssContent)}`,
`__vite__updateStyle(__vite__id, __vite__css)`,
// css modules exports change on edit so it can't self accept
`${modulesCode || 'import.meta.hot.accept()'}`,
`import.meta.hot.prune(() => __vite__removeStyle(__vite__id))`,
].join('\n')
return { code, map: { mappings: '' }, moduleType: 'js' }
}
// build CSS handling ----------------------------------------------------
// record css
if (!inlined) {
styles.set(id, css)
}
let code: string
if (modulesCode) {
code = modulesCode
} else if (inlined) {
let content = css
if (config.build.cssMinify) {
content = await minifyCSS(content, config, true)
}
code = `export default ${JSON.stringify(content)}`
} else {
// empty module when it's not a CSS module nor `?inline`
code = ''
}
return {
code,
map: { mappings: '' },
// avoid the css module from being tree-shaken so that we can retrieve
// it in renderChunk()
moduleSideEffects: modulesCode || inlined ? false : 'no-treeshake',
moduleType: 'js',
}
},
},
async renderChunk(code, chunk, opts, meta) {
let chunkCSS: string | undefined
const renderedModules = new Proxy(
{} as Record<string, RenderedModule | undefined>,
{
get(_target, p) {
for (const name in meta.chunks) {
const modules = meta.chunks[name].modules
const module = modules[p as string]
if (module) {
return module
}
}
},
},
)
// the chunk is empty if it's a dynamic entry chunk that only contains a CSS import
const isJsChunkEmpty = code === '' && !chunk.isEntry
let isPureCssChunk = chunk.exports.length === 0
const ids = Object.keys(chunk.modules)
for (const id of ids) {
if (styles.has(id)) {
// ?transform-only is used for ?url and shouldn't be included in normal CSS chunks
if (transformOnlyRE.test(id)) {
continue
}
// If this CSS is scoped to its importers exports, check if those importers exports
// are rendered in the chunks. If they are not, we can skip bundling this CSS.
const cssScopeTo = this.getModuleInfo(id)?.meta?.vite?.cssScopeTo
if (
cssScopeTo &&
!isCssScopeToRendered(cssScopeTo, renderedModules)
) {
continue
}
// a css module contains JS, so it makes this not a pure css chunk
if (cssModuleRE.test(id)) {
isPureCssChunk = false
}
chunkCSS = (chunkCSS || '') + styles.get(id)
} else if (!isJsChunkEmpty) {
// if the module does not have a style, then it's not a pure css chunk.
// this is true because in the `transform` hook above, only modules
// that are css gets added to the `styles` map.
isPureCssChunk = false
}
}
const publicAssetUrlMap = publicAssetUrlCache.get(config)!
// resolve asset URL placeholders to their built file URLs
const resolveAssetUrlsInCss = (
chunkCSS: string,
cssAssetName: string,
) => {
const encodedPublicUrls = encodePublicUrlsInCSS(config)
const relative = config.base === './' || config.base === ''
const cssAssetDirname =
encodedPublicUrls || relative
? slash(getCssAssetDirname(cssAssetName))
: undefined
const toRelative = (filename: string) => {
// relative base + extracted CSS
const relativePath = normalizePath(
path.relative(cssAssetDirname!, filename),
)
return relativePath[0] === '.' ? relativePath : './' + relativePath
}
// replace asset url references with resolved url.
chunkCSS = chunkCSS.replace(assetUrlRE, (_, fileHash, postfix = '') => {
const filename = this.getFileName(fileHash) + postfix
chunk.viteMetadata!.importedAssets.add(cleanUrl(filename))
return encodeURIPath(
toOutputFilePathInCss(
filename,
'asset',
cssAssetName,
'css',
config,
toRelative,
),
)
})
// resolve public URL from CSS paths
if (encodedPublicUrls) {
const relativePathToPublicFromCSS = normalizePath(
path.relative(cssAssetDirname!, ''),
)
chunkCSS = chunkCSS.replace(publicAssetUrlRE, (_, hash) => {
const publicUrl = publicAssetUrlMap.get(hash)!.slice(1)
return encodeURIPath(
toOutputFilePathInCss(
publicUrl,
'public',
cssAssetName,
'css',
config,
() => `${relativePathToPublicFromCSS}/${publicUrl}`,
),
)
})
}
return chunkCSS
}
function ensureFileExt(name: string, ext: string) {
return normalizePath(
path.format({ ...path.parse(name), base: undefined, ext }),
)
}
let s: MagicString | undefined
const urlEmitTasks: Array<{
cssAssetName: string
originalFileName: string
content: string
start: number
end: number
}> = []
if (code.includes('__VITE_CSS_URL__')) {
let match: RegExpExecArray | null
cssUrlAssetRE.lastIndex = 0
while ((match = cssUrlAssetRE.exec(code))) {
const [full, idHex] = match
const id = Buffer.from(idHex, 'hex').toString()
const originalFileName = cleanUrl(id)
const cssAssetName = ensureFileExt(
path.basename(originalFileName),
'.css',
)
if (!styles.has(id)) {
throw new Error(
`css content for ${JSON.stringify(id)} was not found`,
)
}
let cssContent = styles.get(id)!
cssContent = resolveAssetUrlsInCss(cssContent, cssAssetName)
urlEmitTasks.push({
cssAssetName,
originalFileName,
content: cssContent,
start: match.index,
end: match.index + full.length,
})
}
}
// should await even if this chunk does not include __VITE_CSS_URL__
// so that code after this line runs in the same order
await urlEmitQueue.run(async () =>
Promise.all(
urlEmitTasks.map(async (info) => {
info.content = await finalizeCss(info.content, config)
}),
),
)
if (urlEmitTasks.length > 0) {
const toRelativeRuntime = createToImportMetaURLBasedRelativeRuntime(
opts.format,
config.isWorker,
)
s ||= new MagicString(code)
for (const {
cssAssetName,
originalFileName,
content,
start,
end,
} of urlEmitTasks) {
const referenceId = this.emitFile({
type: 'asset',
name: cssAssetName,
originalFileName,
source: content,
})
const filename = this.getFileName(referenceId)
chunk.viteMetadata!.importedAssets.add(cleanUrl(filename))
const replacement = toOutputFilePathInJS(
this.environment,
filename,
'asset',
chunk.fileName,
'js',
toRelativeRuntime,
)
const replacementString =
typeof replacement === 'string'
? JSON.stringify(encodeURIPath(replacement)).slice(1, -1)
: `"+${replacement.runtime}+"`
s.update(start, end, replacementString)
}
}
if (chunkCSS !== undefined) {
if (isPureCssChunk && (opts.format === 'es' || opts.format === 'cjs')) {
// this is a shared CSS-only chunk that is empty.
pureCssChunks.add(chunk)
}
if (this.environment.config.build.cssCodeSplit) {
if (
(opts.format === 'es' || opts.format === 'cjs') &&
!chunk.fileName.includes('-legacy')
) {
const isEntry = chunk.isEntry && isPureCssChunk
const cssFullAssetName = ensureFileExt(chunk.name, '.css')
// if facadeModuleId doesn't exist or doesn't have a CSS extension,
// that means a JS entry file imports a CSS file.
// in this case, only use the filename for the CSS chunk name like JS chunks.
const cssAssetName =
chunk.isEntry &&
(!chunk.facadeModuleId || !isCSSRequest(chunk.facadeModuleId))
? path.basename(cssFullAssetName)
: cssFullAssetName
const originalFileName = getChunkOriginalFileName(
chunk,
config.root,
this.environment.config.isOutputOptionsForLegacyChunks?.(opts) ??
false,
)
chunkCSS = resolveAssetUrlsInCss(chunkCSS, cssAssetName)
// wait for previous tasks as well
chunkCSS = await codeSplitEmitQueue.run(async () => {
return finalizeCss(chunkCSS!, config)
})
// emit corresponding css file
const referenceId = this.emitFile({
type: 'asset',
name: cssAssetName,
originalFileName,
source: chunkCSS,
})
if (isEntry) {
cssEntriesMap.get(this.environment)!.set(chunk.name, referenceId)
}
chunk.viteMetadata!.importedCss.add(this.getFileName(referenceId))
} else if (this.environment.config.consumer === 'client') {
// legacy build and inline css
// Entry chunk CSS will be collected into `chunk.viteMetadata.importedCss`
// and injected later by the `'vite:build-html'` plugin into the `index.html`
// so it will be duplicated. (https://github.com/vitejs/vite/issues/2062#issuecomment-782388010)
// But because entry chunk can be imported by dynamic import,
// we shouldn't remove the inlined CSS. (#10285)
chunkCSS = await finalizeCss(chunkCSS, config)
let cssString = JSON.stringify(chunkCSS)
cssString =
renderAssetUrlInJS(this, chunk, opts, cssString)?.toString() ||
cssString
const style = `__vite_style__`
const injectCode =
`var ${style} = document.createElement('style');` +
`${style}.textContent = ${cssString};` +
`document.head.appendChild(${style});`
let injectionPoint: number
if (opts.format === 'iife' || opts.format === 'umd') {
const m = (
opts.format === 'iife' ? IIFE_BEGIN_RE : UMD_BEGIN_RE
).exec(code)
if (!m) {
this.error('Injection point for inlined CSS not found')
return
}
injectionPoint = m.index + m[0].length
} else if (opts.format === 'es') {
// legacy build
if (code.startsWith('#!')) {
let secondLinePos = code.indexOf('\n')
if (secondLinePos === -1) {