-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
CSSPackager.js
101 lines (92 loc) 路 2.45 KB
/
CSSPackager.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
// @flow
import path from 'path';
import SourceMap from '@parcel/source-map';
import {Packager} from '@parcel/plugin';
import {
PromiseQueue,
countLines,
replaceInlineReferences,
replaceURLReferences,
} from '@parcel/utils';
export default new Packager({
async package({
bundle,
bundleGraph,
getInlineBundleContents,
options,
getSourceMapReference,
}) {
let queue = new PromiseQueue({maxConcurrent: 32});
bundle.traverseAssets({
exit: asset => {
// Figure out which media types this asset was imported with.
// We only want to import the asset once, so group them all together.
let media = [];
for (let dep of bundleGraph.getIncomingDependencies(asset)) {
if (!dep.meta.media) {
// Asset was imported without a media type. Don't wrap in @media.
media.length = 0;
break;
}
media.push(dep.meta.media);
}
queue.add(() =>
Promise.all([
asset,
asset.getCode().then((css: string) => {
if (media.length) {
return `@media ${media.join(', ')} {\n${css}\n}\n`;
}
return css;
}),
options.sourceMaps && asset.getMapBuffer(),
]),
);
},
});
let outputs = await queue.run();
let contents = '';
let map = new SourceMap();
let lineOffset = 0;
for (let [asset, code, mapBuffer] of outputs) {
contents += code + '\n';
if (options.sourceMaps) {
if (mapBuffer) {
map.addBufferMappings(mapBuffer, lineOffset);
} else {
map.addEmptyMap(
path
.relative(options.projectRoot, asset.filePath)
.replace(/\\+/g, '/'),
code,
lineOffset,
);
}
lineOffset += countLines(code) + 1;
}
}
if (options.sourceMaps) {
let reference = await getSourceMapReference(map);
if (reference != null) {
contents += '/*# sourceMappingURL=' + reference + ' */\n';
}
}
({contents, map} = replaceURLReferences({
bundle,
bundleGraph,
contents,
map,
}));
return replaceInlineReferences({
bundle,
bundleGraph,
contents,
getInlineBundleContents,
getInlineReplacement: (dep, inlineType, contents) => ({
from: dep.id,
to: contents,
}),
map,
});
},
});