/
CSSOptimizer.js
209 lines (190 loc) Β· 5.54 KB
/
CSSOptimizer.js
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
// @flow strict-local
import SourceMap from '@parcel/source-map';
import {Optimizer} from '@parcel/plugin';
import {
transform,
transformStyleAttribute,
browserslistToTargets,
} from 'lightningcss';
import {blobToBuffer} from '@parcel/utils';
import browserslist from 'browserslist';
import nullthrows from 'nullthrows';
import path from 'path';
import {md, generateJSONCodeHighlights} from '@parcel/diagnostic';
export default (new Optimizer({
async loadConfig({config, logger, options}) {
const configFile = await config.getConfig(
[
'.cssnanorc',
'cssnano.config.json',
'cssnano.config.js',
'cssnano.config.cjs',
],
{
packageKey: 'cssnano',
},
);
if (configFile) {
let filename = path.basename(configFile.filePath);
let codeHighlights;
let message;
if (filename === 'package.json') {
message = md`
Parcel\'s default CSS minifer changed from cssnano to lightningcss, but a "cssnano" key was found in **package.json**. Either remove this configuration, or configure Parcel to use @parcel/optimizer-cssnano instead.
`;
let contents = await options.inputFS.readFile(
configFile.filePath,
'utf8',
);
codeHighlights = generateJSONCodeHighlights(contents, [
{key: '/cssnano', type: 'key'},
]);
} else {
message = md`Parcel\'s default CSS minifer changed from cssnano to lightningcss, but a __${filename}__ config file was found. Either remove this config file, or configure Parcel to use @parcel/optimizer-cssnano instead.`;
codeHighlights = [
{
start: {line: 1, column: 1},
end: {line: 1, column: 1},
},
];
}
logger.warn({
message,
documentationURL: 'https://parceljs.org/languages/css/#minification',
codeFrames: [
{
filePath: configFile.filePath,
codeHighlights,
},
],
});
}
},
async optimize({
bundle,
bundleGraph,
logger,
contents: prevContents,
getSourceMapReference,
map: prevMap,
options,
}) {
if (!bundle.env.shouldOptimize) {
return {contents: prevContents, map: prevMap};
}
let targets = getTargets(bundle.env.engines.browsers);
let code = await blobToBuffer(prevContents);
let unusedSymbols;
if (bundle.env.shouldScopeHoist) {
unusedSymbols = [];
bundle.traverseAssets(asset => {
if (
asset.symbols.isCleared ||
asset.meta.cssModulesCompiled === 'postcss'
) {
return;
}
let usedSymbols = bundleGraph.getUsedSymbols(asset);
if (usedSymbols == null) {
return;
}
let defaultImport = null;
if (usedSymbols.has('default')) {
let incoming = bundleGraph.getIncomingDependencies(asset);
defaultImport = incoming.find(d =>
d.symbols.hasExportSymbol('default'),
);
if (defaultImport) {
let loc = defaultImport.symbols.get('default')?.loc;
logger.warn({
message:
'CSS modules cannot be tree shaken when imported with a default specifier',
...(loc && {
codeFrames: [
{
filePath: nullthrows(
loc?.filePath ?? defaultImport.sourcePath,
),
codeHighlights: [{start: loc.start, end: loc.end}],
},
],
}),
hints: [
`Instead do: import * as style from "${defaultImport.specifier}";`,
],
documentationURL:
'https://parceljs.org/languages/css/#tree-shaking',
});
}
}
if (!defaultImport && !usedSymbols.has('*')) {
for (let [symbol, {local}] of asset.symbols) {
if (local !== 'default' && !usedSymbols.has(symbol)) {
unusedSymbols.push(local);
}
}
}
});
}
// Inline style attributes in HTML need to be parsed differently from full CSS files.
if (bundle.bundleBehavior === 'inline') {
let entry = bundle.getMainEntry();
if (entry?.meta.type === 'attr') {
let result = transformStyleAttribute({
code,
minify: true,
targets,
});
return {
contents: result.code,
};
}
}
let result = transform({
filename: bundle.name,
code,
minify: true,
sourceMap: !!bundle.env.sourceMap,
targets,
unusedSymbols,
});
let map;
if (result.map != null) {
let vlqMap = JSON.parse(result.map.toString());
map = new SourceMap(options.projectRoot);
map.addVLQMap(vlqMap);
if (prevMap) {
map.extends(prevMap);
}
}
let contents = result.code;
if (bundle.env.sourceMap) {
let reference = await getSourceMapReference(map);
if (reference != null) {
contents =
contents.toString() +
'\n' +
'/*# sourceMappingURL=' +
reference +
' */\n';
}
}
return {
contents,
map,
};
},
}): Optimizer);
let cache = new Map();
function getTargets(browsers) {
if (browsers == null) {
return undefined;
}
let cached = cache.get(browsers);
if (cached != null) {
return cached;
}
let targets = browserslistToTargets(browserslist(browsers));
cache.set(browsers, targets);
return targets;
}