|
1 | | -import { |
2 | | - createCssPostHooks, |
3 | | - getCleanId, |
4 | | - RE_CSS, |
5 | | - type CssStyles, |
6 | | -} from 'tsdown/css' |
| 1 | +import path from 'node:path' |
| 2 | +import { CssPostPlugin, getCleanId, RE_CSS, type CssStyles } from 'tsdown/css' |
7 | 3 | import { |
8 | 4 | bundleWithLightningCSS, |
9 | 5 | transformWithLightningCSS, |
10 | 6 | } from './lightningcss.ts' |
11 | 7 | import { processWithPostCSS as runPostCSS } from './postcss.ts' |
12 | | -import { |
13 | | - compilePreprocessor, |
14 | | - getPreprocessorLang, |
15 | | - isCssOrPreprocessor, |
16 | | -} from './preprocessors.ts' |
| 8 | +import { compilePreprocessor, getPreprocessorLang } from './preprocessors.ts' |
17 | 9 | import type { MinimalLogger } from './types.ts' |
18 | 10 | import type { Plugin } from 'rolldown' |
19 | 11 | import type { ResolvedConfig } from 'tsdown' |
20 | 12 |
|
| 13 | +const CSS_LANGS_RE = /\.(?:css|less|sass|scss|styl|stylus)$/ |
| 14 | + |
21 | 15 | export function CssPlugin( |
22 | 16 | config: ResolvedConfig, |
23 | 17 | { logger }: { logger: MinimalLogger }, |
24 | | -): Plugin { |
| 18 | +): Plugin[] { |
25 | 19 | const styles: CssStyles = new Map() |
26 | | - const postHooks = createCssPostHooks(config, styles) |
27 | 20 |
|
28 | | - return { |
| 21 | + const transformPlugin: Plugin = { |
29 | 22 | name: '@tsdown/css', |
30 | 23 |
|
31 | 24 | buildStart() { |
32 | 25 | styles.clear() |
33 | 26 | }, |
34 | 27 |
|
35 | | - async transform(code, id) { |
36 | | - if (!isCssOrPreprocessor(id)) return |
37 | | - |
38 | | - const cleanId = getCleanId(id) |
39 | | - const deps: string[] = [] |
40 | | - |
41 | | - if (config.css.transformer === 'lightningcss') { |
42 | | - code = await processWithLightningCSS( |
43 | | - code, |
44 | | - id, |
45 | | - cleanId, |
46 | | - deps, |
47 | | - config, |
48 | | - logger, |
49 | | - ) |
50 | | - } else { |
51 | | - code = await processWithPostCSS(code, id, cleanId, deps, config) |
52 | | - } |
53 | | - |
54 | | - for (const dep of deps) { |
55 | | - this.addWatchFile(dep) |
56 | | - } |
57 | | - |
58 | | - if (code.length && !code.endsWith('\n')) { |
59 | | - code += '\n' |
60 | | - } |
61 | | - |
62 | | - styles.set(id, code) |
63 | | - return { |
64 | | - code: '', |
65 | | - moduleSideEffects: 'no-treeshake', |
66 | | - moduleType: 'js', |
67 | | - } |
| 28 | + transform: { |
| 29 | + filter: { id: CSS_LANGS_RE }, |
| 30 | + async handler(code, id) { |
| 31 | + const cleanId = getCleanId(id) |
| 32 | + const deps: string[] = [] |
| 33 | + |
| 34 | + if (config.css.transformer === 'lightningcss') { |
| 35 | + code = await processWithLightningCSS( |
| 36 | + code, |
| 37 | + id, |
| 38 | + cleanId, |
| 39 | + deps, |
| 40 | + config, |
| 41 | + logger, |
| 42 | + ) |
| 43 | + } else { |
| 44 | + code = await processWithPostCSS(code, id, cleanId, deps, config) |
| 45 | + } |
| 46 | + |
| 47 | + for (const dep of deps) { |
| 48 | + this.addWatchFile(dep) |
| 49 | + } |
| 50 | + |
| 51 | + if (code.length && !code.endsWith('\n')) { |
| 52 | + code += '\n' |
| 53 | + } |
| 54 | + |
| 55 | + styles.set(id, code) |
| 56 | + return { |
| 57 | + code: '', |
| 58 | + moduleSideEffects: 'no-treeshake', |
| 59 | + moduleType: 'js', |
| 60 | + } |
| 61 | + }, |
68 | 62 | }, |
| 63 | + } |
69 | 64 |
|
70 | | - ...postHooks, |
| 65 | + const plugins: Plugin[] = [transformPlugin] |
| 66 | + |
| 67 | + if (config.css.inject) { |
| 68 | + // Inject plugin runs BEFORE CssPostPlugin so it can see pure CSS chunks |
| 69 | + // before they are removed, and rewrite their imports to CSS asset paths. |
| 70 | + const injectPlugin: Plugin = { |
| 71 | + name: '@tsdown/css:inject', |
| 72 | + |
| 73 | + generateBundle(_outputOptions, bundle) { |
| 74 | + const chunks = Object.values(bundle) |
| 75 | + // Identify pure CSS chunks and empty CSS wrapper chunks |
| 76 | + const pureCssChunks = new Set<string>() |
| 77 | + for (const chunk of chunks) { |
| 78 | + if ( |
| 79 | + chunk.type !== 'chunk' || |
| 80 | + chunk.exports.length || |
| 81 | + !chunk.moduleIds.length || |
| 82 | + chunk.isEntry || |
| 83 | + chunk.isDynamicEntry |
| 84 | + ) |
| 85 | + continue |
| 86 | + // Strict: all modules are CSS |
| 87 | + if (chunk.moduleIds.every((id) => styles.has(id))) { |
| 88 | + pureCssChunks.add(chunk.fileName) |
| 89 | + continue |
| 90 | + } |
| 91 | + // Relaxed: chunk has CSS modules and code is trivially empty |
| 92 | + // (e.g. a JS file whose only purpose is `import './foo.css'`) |
| 93 | + if ( |
| 94 | + chunk.moduleIds.some((id) => styles.has(id)) && |
| 95 | + isEmptyChunkCode(chunk.code) |
| 96 | + ) { |
| 97 | + pureCssChunks.add(chunk.fileName) |
| 98 | + } |
| 99 | + } |
| 100 | + |
| 101 | + for (const chunk of chunks) { |
| 102 | + if (chunk.type !== 'chunk') continue |
| 103 | + if (pureCssChunks.has(chunk.fileName)) continue |
| 104 | + |
| 105 | + if (config.css.splitting) { |
| 106 | + // Rewrite pure CSS chunk imports in-place: swap .mjs/.cjs/.js → .css |
| 107 | + // This preserves import order and sourcemap line positions. |
| 108 | + for (const imp of chunk.imports) { |
| 109 | + if (!pureCssChunks.has(imp)) continue |
| 110 | + const basename = path.basename(imp) |
| 111 | + const escaped = basename.replaceAll( |
| 112 | + /[.*+?^${}()|[\]\\]/g, |
| 113 | + String.raw`\$&`, |
| 114 | + ) |
| 115 | + const cssBasename = basename.replace(/\.[cm]?js$/, '.css') |
| 116 | + const importRE = new RegExp( |
| 117 | + String.raw`(\bimport\s*["'][^"']*)${escaped}(["'];)`, |
| 118 | + ) |
| 119 | + chunk.code = chunk.code.replace(importRE, `$1${cssBasename}$2`) |
| 120 | + } |
| 121 | + // Direct CSS modules in this chunk need a prepended import |
| 122 | + if (chunk.moduleIds.some((id) => styles.has(id))) { |
| 123 | + const cssFile = chunk.fileName.replace(/\.[cm]?js$/, '.css') |
| 124 | + const relativePath = path.posix.relative( |
| 125 | + path.posix.dirname(chunk.fileName), |
| 126 | + cssFile, |
| 127 | + ) |
| 128 | + const importPath = |
| 129 | + relativePath[0] === '.' ? relativePath : `./${relativePath}` |
| 130 | + chunk.code = `import '${importPath}';\n${chunk.code}` |
| 131 | + if (chunk.map) { |
| 132 | + chunk.map.mappings = `;${chunk.map.mappings}` |
| 133 | + } |
| 134 | + } |
| 135 | + } else { |
| 136 | + const hasCss = |
| 137 | + chunk.moduleIds.some((id) => styles.has(id)) || |
| 138 | + chunk.imports.some((imp) => pureCssChunks.has(imp)) |
| 139 | + if (hasCss) { |
| 140 | + const cssFile = config.css.fileName |
| 141 | + const relativePath = path.posix.relative( |
| 142 | + path.posix.dirname(chunk.fileName), |
| 143 | + cssFile, |
| 144 | + ) |
| 145 | + const importPath = |
| 146 | + relativePath[0] === '.' ? relativePath : `./${relativePath}` |
| 147 | + chunk.code = `import '${importPath}';\n${chunk.code}` |
| 148 | + if (chunk.map) { |
| 149 | + chunk.map.mappings = `;${chunk.map.mappings}` |
| 150 | + } |
| 151 | + } |
| 152 | + } |
| 153 | + } |
| 154 | + }, |
| 155 | + } |
| 156 | + plugins.push(injectPlugin) |
71 | 157 | } |
| 158 | + |
| 159 | + plugins.push(CssPostPlugin(config.css, styles)) |
| 160 | + return plugins |
72 | 161 | } |
73 | 162 |
|
74 | 163 | async function processWithLightningCSS( |
@@ -162,3 +251,12 @@ async function processWithPostCSS( |
162 | 251 | minify: config.css.minify, |
163 | 252 | }) |
164 | 253 | } |
| 254 | + |
| 255 | +function isEmptyChunkCode(code: string): boolean { |
| 256 | + return !code |
| 257 | + .replaceAll(/\/\*[\s\S]*?\*\//g, '') |
| 258 | + .replaceAll(/\/\/[^\n]*/g, '') |
| 259 | + .replaceAll(/\bexport\s*\{\s*\};?/g, '') |
| 260 | + .replaceAll(/\bimport\s*["'][^"']*["'];?/g, '') |
| 261 | + .trim() |
| 262 | +} |
0 commit comments