/
plugin-css.ts
260 lines (239 loc) · 8.48 KB
/
plugin-css.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
import * as crypto from 'node:crypto';
import * as npath from 'node:path';
import type { GetModuleInfo } from 'rollup';
import { type Plugin as VitePlugin, type ResolvedConfig } from 'vite';
import { isBuildableCSSRequest } from '../../render/dev/util.js';
import type { BuildInternals } from '../internal';
import type { AstroBuildPlugin } from '../plugin';
import type { PageBuildData, StaticBuildOptions } from '../types';
import { PROPAGATED_ASSET_FLAG } from '../../../content/consts.js';
import * as assetName from '../css-asset-name.js';
import { moduleIsTopLevelPage, walkParentInfos } from '../graph.js';
import {
eachPageData,
getPageDataByViteID,
getPageDatasByClientOnlyID,
getPageDatasByHoistedScriptId,
isHoistedScript,
} from '../internal.js';
import { extendManualChunks } from './util.js';
interface PluginOptions {
internals: BuildInternals;
buildOptions: StaticBuildOptions;
target: 'client' | 'server';
}
export function rollupPluginAstroBuildCSS(options: PluginOptions): VitePlugin[] {
const { internals, buildOptions } = options;
const { settings } = buildOptions;
let resolvedConfig: ResolvedConfig;
function createNameHash(baseId: string, hashIds: string[]): string {
const baseName = baseId ? npath.parse(baseId).name : 'index';
const hash = crypto.createHash('sha256');
for (const id of hashIds) {
hash.update(id, 'utf-8');
}
const h = hash.digest('hex').slice(0, 8);
const proposedName = baseName + '.' + h;
return proposedName;
}
function* getParentClientOnlys(
id: string,
ctx: { getModuleInfo: GetModuleInfo }
): Generator<PageBuildData, void, unknown> {
for (const [info] of walkParentInfos(id, ctx)) {
yield* getPageDatasByClientOnlyID(internals, info.id);
}
}
return [
{
name: 'astro:rollup-plugin-build-css',
transform(_, id) {
// In the SSR build, styles that are bundled are tracked in `internals.cssChunkModuleIds`.
// In the client build, if we're also bundling the same style, return an empty string to
// deduplicate the final CSS output.
if (options.target === 'client' && internals.cssChunkModuleIds.has(id)) {
return '';
}
},
outputOptions(outputOptions) {
// Skip in client builds as its module graph doesn't have reference to Astro pages
// to be able to chunk based on it's related top-level pages.
if (options.target === 'client') return;
const assetFileNames = outputOptions.assetFileNames;
const namingIncludesHash = assetFileNames?.toString().includes('[hash]');
const createNameForParentPages = namingIncludesHash
? assetName.shortHashedName
: assetName.createSlugger(settings);
extendManualChunks(outputOptions, {
after(id, meta) {
// For CSS, create a hash of all of the pages that use it.
// This causes CSS to be built into shared chunks when used by multiple pages.
if (isBuildableCSSRequest(id)) {
for (const [pageInfo] of walkParentInfos(id, {
getModuleInfo: meta.getModuleInfo,
})) {
if (new URL(pageInfo.id, 'file://').searchParams.has(PROPAGATED_ASSET_FLAG)) {
// Split delayed assets to separate modules
// so they can be injected where needed
return createNameHash(id, [id]);
}
}
return createNameForParentPages(id, meta);
}
},
});
},
async generateBundle(_outputOptions, bundle) {
type ViteMetadata = {
importedAssets: Set<string>;
importedCss: Set<string>;
};
const appendCSSToPage = (
pageData: PageBuildData,
meta: ViteMetadata,
depth: number,
order: number
) => {
for (const importedCssImport of meta.importedCss) {
// CSS is prioritized based on depth. Shared CSS has a higher depth due to being imported by multiple pages.
// Depth info is used when sorting the links on the page.
if (pageData?.css.has(importedCssImport)) {
// eslint-disable-next-line
const cssInfo = pageData?.css.get(importedCssImport)!;
if (depth < cssInfo.depth) {
cssInfo.depth = depth;
}
// Update the order, preferring the lowest order we have.
if (cssInfo.order === -1) {
cssInfo.order = order;
} else if (order < cssInfo.order && order > -1) {
cssInfo.order = order;
}
} else {
pageData?.css.set(importedCssImport, { depth, order });
}
}
};
for (const [_, chunk] of Object.entries(bundle)) {
if (chunk.type === 'chunk') {
const c = chunk;
if ('viteMetadata' in chunk) {
const meta = chunk['viteMetadata'] as ViteMetadata;
// Chunks that have the viteMetadata.importedCss are CSS chunks
if (meta.importedCss.size) {
// In the SSR build, keep track of all CSS chunks' modules as the client build may
// duplicate them, e.g. for `client:load` components that render in SSR and client
// for hydation.
if (options.target === 'server') {
for (const id of Object.keys(c.modules)) {
internals.cssChunkModuleIds.add(id);
}
}
// For the client build, client:only styles need to be mapped
// over to their page. For this chunk, determine if it's a child of a
// client:only component and if so, add its CSS to the page it belongs to.
if (options.target === 'client') {
for (const id of Object.keys(c.modules)) {
for (const pageData of getParentClientOnlys(id, this)) {
for (const importedCssImport of meta.importedCss) {
pageData.css.set(importedCssImport, { depth: -1, order: -1 });
}
}
}
}
// For this CSS chunk, walk parents until you find a page. Add the CSS to that page.
for (const id of Object.keys(c.modules)) {
for (const [pageInfo, depth, order] of walkParentInfos(
id,
this,
function until(importer) {
return new URL(importer, 'file://').searchParams.has(PROPAGATED_ASSET_FLAG);
}
)) {
if (new URL(pageInfo.id, 'file://').searchParams.has(PROPAGATED_ASSET_FLAG)) {
for (const parent of walkParentInfos(id, this)) {
const parentInfo = parent[0];
if (moduleIsTopLevelPage(parentInfo)) {
const pageViteID = parentInfo.id;
const pageData = getPageDataByViteID(internals, pageViteID);
if (pageData) {
for (const css of meta.importedCss) {
const existingCss =
pageData.propagatedStyles.get(pageInfo.id) ?? new Set();
pageData.propagatedStyles.set(
pageInfo.id,
new Set([...existingCss, css])
);
}
}
}
}
} else if (moduleIsTopLevelPage(pageInfo)) {
const pageViteID = pageInfo.id;
const pageData = getPageDataByViteID(internals, pageViteID);
if (pageData) {
appendCSSToPage(pageData, meta, depth, order);
}
} else if (
options.target === 'client' &&
isHoistedScript(internals, pageInfo.id)
) {
for (const pageData of getPageDatasByHoistedScriptId(
internals,
pageInfo.id
)) {
appendCSSToPage(pageData, meta, -1, order);
}
}
}
}
}
}
}
}
},
},
{
name: 'astro:rollup-plugin-single-css',
enforce: 'post',
configResolved(config) {
resolvedConfig = config;
},
generateBundle(_, bundle) {
// If user disable css code-splitting, search for Vite's hardcoded
// `style.css` and add it as css for each page.
// Ref: https://github.com/vitejs/vite/blob/b2c0ee04d4db4a0ef5a084c50f49782c5f88587c/packages/vite/src/node/plugins/html.ts#L690-L705
if (!resolvedConfig.build.cssCodeSplit) {
const cssChunk = Object.values(bundle).find(
(chunk) => chunk.type === 'asset' && chunk.name === 'style.css'
);
if (cssChunk) {
for (const pageData of eachPageData(internals)) {
pageData.css.set(cssChunk.fileName, { depth: -1, order: -1 });
}
}
}
},
},
];
}
export function pluginCSS(
options: StaticBuildOptions,
internals: BuildInternals
): AstroBuildPlugin {
return {
build: 'both',
hooks: {
'build:before': ({ build }) => {
let plugins = rollupPluginAstroBuildCSS({
buildOptions: options,
internals,
target: build === 'ssr' ? 'server' : 'client',
});
return {
vitePlugin: plugins,
};
},
},
};
}