-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
CSSNanoOptimizer.js
66 lines (58 loc) 路 1.69 KB
/
CSSNanoOptimizer.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
// @flow strict-local
import SourceMap from '@parcel/source-map';
import {Optimizer} from '@parcel/plugin';
import postcss from 'postcss';
// flowlint-next-line untyped-import:off
import cssnano from 'cssnano';
const sentinelPath = '@@parcel-cssnano-optimizer';
export default new Optimizer({
async optimize({
bundle,
contents: prevContents,
getSourceMapReference,
map: prevMap,
options,
}) {
if (!bundle.env.minify) {
return {contents: prevContents, map: prevMap};
}
if (typeof prevContents !== 'string') {
throw new Error(
'CSSNanoOptimizer: Only string contents are currently supported',
);
}
const result = await postcss([cssnano]).process(prevContents, {
// Postcss uses a `from` path and seems to include it as a source.
// In our case, the previous map contains all the needed sources.
// Provide a known sentinel path to use as the source, and filter it out
// from the produced sources below.
from: sentinelPath,
map: {
annotation: false,
inline: false,
prev: prevMap ? await prevMap.stringify({}) : null,
},
});
let map;
if (result.map != null) {
map = new SourceMap();
let {mappings, sources, names} = result.map.toJSON();
map.addRawMappings(
mappings,
sources.filter(source => source !== sentinelPath),
names,
);
}
let contents = result.css;
if (options.sourceMaps) {
let reference = await getSourceMapReference(map);
if (reference != null) {
contents += '\n' + '/*# sourceMappingURL=' + reference + ' */\n';
}
}
return {
contents,
map,
};
},
});