-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
stylesheet-processor.ts
313 lines (270 loc) · 8.54 KB
/
stylesheet-processor.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
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
/**
* Adapted from the original ng-packagr source.
*
* Changes made:
* - Added the filePath parameter to the cache key.
* - Refactored caching to take into account TailwindCSS processing.
* - Added PostCSS plugins needed to support TailwindCSS.
* - Added watch mode parameter.
*/
import * as browserslist from 'browserslist';
import { existsSync } from 'fs';
import { EsbuildExecutor } from 'ng-packagr/lib/esbuild/esbuild-executor';
import {
generateKey,
readCacheEntry,
saveCacheEntry,
} from 'ng-packagr/lib/utils/cache';
import * as log from 'ng-packagr/lib/utils/log';
import { dirname, extname, join } from 'path';
import * as postcssPresetEnv from 'postcss-preset-env';
import * as postcssUrl from 'postcss-url';
import {
getTailwindPostCssPlugins,
getTailwindSetup,
tailwindDirectives,
TailwindSetup,
} from '../../../utilities/tailwindcss';
import { pathToFileURL } from 'url';
const postcss = require('postcss');
export enum CssUrl {
inline = 'inline',
none = 'none',
}
export interface Result {
css: string;
warnings: string[];
error?: string;
}
export class StylesheetProcessor {
private browserslistData: string[];
private targets: string[];
private postCssProcessor: ReturnType<typeof postcss>;
private esbuild = new EsbuildExecutor();
private styleIncludePaths: string[];
private tailwindSetup: TailwindSetup | undefined;
constructor(
private readonly basePath: string,
private readonly cssUrl?: CssUrl,
private readonly includePaths?: string[],
private readonly cacheDirectory?: string | false,
private readonly watch?: boolean,
private readonly tailwindConfig?: string
) {
// By default, browserslist defaults are too inclusive
// https://github.com/browserslist/browserslist/blob/83764ea81ffaa39111c204b02c371afa44a4ff07/index.js#L516-L522
// We change the default query to browsers that Angular support.
// https://angular.io/guide/browser-support
(browserslist.defaults as string[]) = [
'last 1 Chrome version',
'last 1 Firefox version',
'last 2 Edge major versions',
'last 2 Safari major versions',
'last 2 iOS major versions',
'Firefox ESR',
];
this.styleIncludePaths = [...this.includePaths];
let prevDir = null;
let currentDir = this.basePath;
while (currentDir !== prevDir) {
const p = join(currentDir, 'node_modules');
if (existsSync(p)) {
this.styleIncludePaths.push(p);
}
prevDir = currentDir;
currentDir = dirname(prevDir);
}
this.browserslistData = browserslist(undefined, { path: this.basePath });
this.targets = transformSupportedBrowsersToTargets(this.browserslistData);
this.tailwindSetup = getTailwindSetup(this.basePath, this.tailwindConfig);
this.postCssProcessor = this.createPostCssPlugins();
}
async process({
filePath,
content,
}: {
filePath: string;
content: string;
}): Promise<string> {
let key: string | undefined;
if (
this.cacheDirectory &&
!content.includes('@import') &&
!content.includes('@use') &&
!this.containsTailwindDirectives(content)
) {
// No transitive deps and no Tailwind directives, we can cache more aggressively.
key = await generateKey(content, ...this.browserslistData, filePath);
const result = await readCacheEntry(this.cacheDirectory, key);
if (result) {
result.warnings.forEach((msg) => log.warn(msg));
return result.css;
}
}
// Render pre-processor language (sass, styl, less)
const renderedCss = await this.renderCss(filePath, content);
let containsTailwindDirectives = false;
if (this.cacheDirectory) {
containsTailwindDirectives = this.containsTailwindDirectives(renderedCss);
if (!containsTailwindDirectives) {
// No Tailwind directives to process by PostCSS, we can return cached results
if (!key) {
key = await generateKey(
renderedCss,
...this.browserslistData,
filePath
);
}
const cachedResult = await this.getCachedResult(key);
if (cachedResult) {
return cachedResult;
}
}
}
// Render postcss (autoprefixing and friends)
const result = await this.postCssProcessor.process(renderedCss, {
from: filePath,
to: filePath.replace(extname(filePath), '.css'),
});
if (this.cacheDirectory && containsTailwindDirectives) {
// We had Tailwind directives to process by PostCSS, only now
// is safe to return cached results
key = await generateKey(result.css, ...this.browserslistData, filePath);
const cachedResult = await this.getCachedResult(key);
if (cachedResult) {
return cachedResult;
}
}
const warnings = result.warnings().map((w) => w.toString());
const { code, warnings: esBuildWarnings } = await this.esbuild.transform(
result.css,
{
loader: 'css',
minify: true,
target: this.targets,
sourcefile: filePath,
}
);
if (esBuildWarnings.length > 0) {
warnings.push(
...(await this.esbuild.formatMessages(esBuildWarnings, {
kind: 'warning',
}))
);
}
if (this.cacheDirectory) {
await saveCacheEntry(
this.cacheDirectory,
key,
JSON.stringify({
css: code,
warnings,
})
);
}
warnings.forEach((msg) => log.warn(msg));
return code;
}
private async getCachedResult(key: string): Promise<string | undefined> {
const cachedResult = await readCacheEntry(
this.cacheDirectory as string,
key
);
if (cachedResult) {
cachedResult.warnings.forEach((msg) => log.warn(msg));
return cachedResult.css;
}
return undefined;
}
private containsTailwindDirectives(content: string): boolean {
return (
this.tailwindSetup && tailwindDirectives.some((d) => content.includes(d))
);
}
private createPostCssPlugins(): ReturnType<typeof postcss> {
const postCssPlugins = [];
if (this.cssUrl !== CssUrl.none) {
postCssPlugins.push(postcssUrl({ url: this.cssUrl }));
}
if (this.tailwindSetup) {
postCssPlugins.push(
...getTailwindPostCssPlugins(
this.tailwindSetup,
this.styleIncludePaths,
this.watch
)
);
}
postCssPlugins.push(
postcssPresetEnv({
browsers: this.browserslistData,
autoprefixer: true,
stage: 3,
})
);
return postcss(postCssPlugins);
}
private async renderCss(filePath: string, css: string): Promise<string> {
const ext = extname(filePath);
switch (ext) {
case '.sass':
case '.scss': {
return (await import('sass'))
.compileString(css, {
url: pathToFileURL(filePath),
syntax: '.sass' === ext ? 'indented' : 'scss',
loadPaths: this.styleIncludePaths,
})
.css.toString();
}
case '.less': {
const { css: content } = await (
await import('less')
).render(css, {
filename: filePath,
math: 'always',
javascriptEnabled: true,
paths: this.styleIncludePaths,
});
return content;
}
case '.css':
default:
return css;
}
}
}
function transformSupportedBrowsersToTargets(
supportedBrowsers: string[]
): string[] {
const transformed: string[] = [];
// https://esbuild.github.io/api/#target
const esBuildSupportedBrowsers = new Set([
'safari',
'firefox',
'edge',
'chrome',
'ios',
]);
for (const browser of supportedBrowsers) {
let [browserName, version] = browser.split(' ');
// browserslist uses the name `ios_saf` for iOS Safari whereas esbuild uses `ios`
if (browserName === 'ios_saf') {
browserName = 'ios';
}
// browserslist uses ranges `15.2-15.3` versions but only the lowest is required
// to perform minimum supported feature checks. esbuild also expects a single version.
[version] = version.split('-');
if (browserName === 'ie') {
transformed.push('edge12');
} else if (esBuildSupportedBrowsers.has(browserName)) {
if (browserName === 'safari' && version === 'TP') {
// esbuild only supports numeric versions so `TP` is converted to a high number (999) since
// a Technology Preview (TP) of Safari is assumed to support all currently known features.
version = '999';
}
transformed.push(browserName + version);
}
}
return transformed.length ? transformed : undefined;
}