|
| 1 | +import { RE_CSS } from 'rolldown-plugin-dts/filename' |
| 2 | +import type { ResolvedConfig } from '../config/index.ts' |
| 3 | +import type { OutputAsset, OutputChunk, Plugin } from 'rolldown' |
| 4 | + |
| 5 | +export interface CssOptions { |
| 6 | + /** |
| 7 | + * Enable/disable CSS code splitting. |
| 8 | + * When set to `false`, all CSS in the entire project will be extracted into a single CSS file. |
| 9 | + * When set to `true`, CSS imported in async JS chunks will be preserved as chunks. |
| 10 | + * @default true |
| 11 | + */ |
| 12 | + splitting?: boolean |
| 13 | + |
| 14 | + /** |
| 15 | + * Specify the name of the CSS file. |
| 16 | + * @default 'style.css' |
| 17 | + */ |
| 18 | + fileName?: string |
| 19 | +} |
| 20 | + |
| 21 | +// Regular expressions for file matching |
| 22 | +const RE_CSS_HASH = /-[\w-]+\.css$/ |
| 23 | +const RE_CHUNK_HASH = /-[\w-]+\.(m?js|cjs)$/ |
| 24 | +const RE_CHUNK_EXT = /\.(m?js|cjs)$/ |
| 25 | + |
| 26 | +export const defaultCssBundleName = 'style.css' |
| 27 | + |
| 28 | +/** |
| 29 | + * Normalize CSS file name by removing hash pattern and extension. |
| 30 | + * e.g., "async-DcjEOEdU.css" -> "async" |
| 31 | + */ |
| 32 | +function normalizeCssFileName(cssFileName: string): string { |
| 33 | + return cssFileName.replace(RE_CSS_HASH, '').replace(RE_CSS, '') |
| 34 | +} |
| 35 | + |
| 36 | +/** |
| 37 | + * Normalize chunk file name by removing hash pattern and extension. |
| 38 | + * e.g., "async-CvIfFAic.mjs" -> "async" |
| 39 | + */ |
| 40 | +function normalizeChunkFileName(chunkFileName: string): string { |
| 41 | + return chunkFileName.replace(RE_CHUNK_HASH, '').replace(RE_CHUNK_EXT, '') |
| 42 | +} |
| 43 | + |
| 44 | +/** |
| 45 | + * CSS Code Split Plugin |
| 46 | + * |
| 47 | + * When css.splitting is false, this plugin merges all CSS files into a single file. |
| 48 | + * When css.splitting is true (default), CSS code splitting is preserved. |
| 49 | + * Based on Vite's implementation. |
| 50 | + */ |
| 51 | +export function CssCodeSplitPlugin( |
| 52 | + config: Pick<ResolvedConfig, 'css'>, |
| 53 | +): Plugin | undefined { |
| 54 | + const { splitting, fileName } = config.css |
| 55 | + if (splitting) return |
| 56 | + |
| 57 | + let hasEmitted = false |
| 58 | + |
| 59 | + return { |
| 60 | + name: 'tsdown:css-code-split', |
| 61 | + |
| 62 | + renderStart() { |
| 63 | + // Reset state for each build for watch mode |
| 64 | + hasEmitted = false |
| 65 | + }, |
| 66 | + |
| 67 | + generateBundle(_outputOptions, bundle) { |
| 68 | + if (hasEmitted) return |
| 69 | + |
| 70 | + // Collect all CSS assets and their content |
| 71 | + const cssAssets = new Map<string, string>() |
| 72 | + |
| 73 | + for (const [fileName, asset] of Object.entries(bundle)) { |
| 74 | + if (asset.type === 'asset' && RE_CSS.test(fileName)) { |
| 75 | + const source = |
| 76 | + typeof asset.source === 'string' |
| 77 | + ? asset.source |
| 78 | + : new TextDecoder('utf-8').decode(asset.source) |
| 79 | + cssAssets.set(fileName, source) |
| 80 | + } |
| 81 | + } |
| 82 | + |
| 83 | + if (!cssAssets.size) return |
| 84 | + |
| 85 | + // Build a map from chunk fileName to its associated CSS fileName(s) |
| 86 | + // Match CSS assets to chunks by analyzing module IDs and file names |
| 87 | + const chunkCSSMap = new Map<string, string[]>() |
| 88 | + |
| 89 | + // Identify which chunks contain CSS modules |
| 90 | + for (const [chunkFileName, item] of Object.entries(bundle)) { |
| 91 | + if (item.type === 'chunk') { |
| 92 | + for (const moduleId of Object.keys(item.modules)) { |
| 93 | + if (RE_CSS.test(moduleId)) { |
| 94 | + if (!chunkCSSMap.has(chunkFileName)) { |
| 95 | + chunkCSSMap.set(chunkFileName, []) |
| 96 | + } |
| 97 | + break |
| 98 | + } |
| 99 | + } |
| 100 | + } |
| 101 | + } |
| 102 | + |
| 103 | + // Match CSS assets to chunks by comparing base names |
| 104 | + for (const [cssFileName] of cssAssets) { |
| 105 | + const cssBaseName = normalizeCssFileName(cssFileName) |
| 106 | + for (const [chunkFileName] of chunkCSSMap) { |
| 107 | + const chunkBaseName = normalizeChunkFileName(chunkFileName) |
| 108 | + if ( |
| 109 | + chunkBaseName === cssBaseName || |
| 110 | + chunkFileName.startsWith(`${cssBaseName}-`) |
| 111 | + ) { |
| 112 | + chunkCSSMap.get(chunkFileName)?.push(cssFileName) |
| 113 | + break |
| 114 | + } |
| 115 | + } |
| 116 | + } |
| 117 | + |
| 118 | + let extractedCss = '' |
| 119 | + const collected = new Set<OutputChunk>() |
| 120 | + const dynamicImports = new Set<string>() |
| 121 | + |
| 122 | + function collect(chunk: OutputChunk | OutputAsset | undefined) { |
| 123 | + if (!chunk || chunk.type !== 'chunk' || collected.has(chunk)) return |
| 124 | + collected.add(chunk) |
| 125 | + |
| 126 | + // Collect all styles from synchronous imports (lowest priority) |
| 127 | + chunk.imports.forEach((importName) => { |
| 128 | + collect(bundle[importName]) |
| 129 | + }) |
| 130 | + |
| 131 | + // Save dynamic imports to add styles later (highest priority) |
| 132 | + chunk.dynamicImports.forEach((importName) => { |
| 133 | + dynamicImports.add(importName) |
| 134 | + }) |
| 135 | + |
| 136 | + // Collect the styles of the current chunk |
| 137 | + const files = chunkCSSMap.get(chunk.fileName) |
| 138 | + if (files && files.length > 0) { |
| 139 | + for (const filename of files) { |
| 140 | + extractedCss += cssAssets.get(filename) ?? '' |
| 141 | + } |
| 142 | + } |
| 143 | + } |
| 144 | + |
| 145 | + // Collect CSS from all entry chunks first |
| 146 | + for (const chunk of Object.values(bundle)) { |
| 147 | + if (chunk.type === 'chunk' && chunk.isEntry) { |
| 148 | + collect(chunk) |
| 149 | + } |
| 150 | + } |
| 151 | + |
| 152 | + // Collect CSS from dynamic imports (highest priority) |
| 153 | + for (const chunkName of dynamicImports) { |
| 154 | + collect(bundle[chunkName]) |
| 155 | + } |
| 156 | + |
| 157 | + if (extractedCss) { |
| 158 | + hasEmitted = true |
| 159 | + |
| 160 | + // Remove all individual CSS assets from bundle |
| 161 | + for (const fileName of cssAssets.keys()) { |
| 162 | + delete bundle[fileName] |
| 163 | + } |
| 164 | + |
| 165 | + this.emitFile({ |
| 166 | + type: 'asset', |
| 167 | + source: extractedCss, |
| 168 | + fileName, |
| 169 | + // this file is an implicit entry point, use `style.css` as the original file name |
| 170 | + originalFileName: defaultCssBundleName, |
| 171 | + }) |
| 172 | + } |
| 173 | + }, |
| 174 | + } |
| 175 | +} |
0 commit comments