()
| 22 | * ``` |
| 23 | */ |
| 24 | export function cssInjectPlugin(): Plugin { |
| 25 | return { |
| 26 | name: 'esengine:css-inject', |
| 27 | apply: 'build', |
| 28 | |
| 29 | generateBundle(_options: NormalizedOutputOptions, bundle: OutputBundle) { |
| 30 | // 收集所有 CSS 内容 |
| 31 | const cssChunks: string[] = []; |
| 32 | const cssFileNames: string[] = []; |
| 33 | |
| 34 | for (const [fileName, chunk] of Object.entries(bundle)) { |
| 35 | if (fileName.endsWith('.css') && chunk.type === 'asset') { |
| 36 | cssChunks.push(chunk.source as string); |
| 37 | cssFileNames.push(fileName); |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | if (cssChunks.length === 0) return; |
| 42 | |
| 43 | // 合并所有 CSS |
| 44 | const combinedCSS = cssChunks.join('\n'); |
| 45 | |
| 46 | // 创建注入代码 |
| 47 | const injectCode = ` |
| 48 | (function() { |
| 49 | if (typeof document === 'undefined') return; |
| 50 | var style = document.createElement('style'); |
| 51 | style.setAttribute('data-esengine', 'true'); |
| 52 | style.textContent = ${JSON.stringify(combinedCSS)}; |
| 53 | document.head.appendChild(style); |
| 54 | })(); |
| 55 | `; |
| 56 | |
| 57 | // 找到主入口 JS 文件并注入 |
| 58 | for (const chunk of Object.values(bundle)) { |
| 59 | if (chunk.type === 'chunk' && chunk.isEntry) { |
| 60 | chunk.code = injectCode + chunk.code; |
| 61 | break; |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | // 删除独立的 CSS 文件 |
| 66 | for (const fileName of cssFileNames) { |
| 67 | delete bundle[fileName]; |
| 68 | } |
| 69 | } |
| 70 | }; |
| 71 | } |
no outgoing calls
no test coverage detected