1 | const path = require('path');
|
2 | const Packager = require('./Packager');
|
3 | const lineCounter = require('../utils/lineCounter');
|
4 | const urlJoin = require('../utils/urlJoin');
|
5 |
|
6 | class CSSPackager extends Packager {
|
7 | async start() {
|
8 | this.lineOffset = 0;
|
9 | this.columnOffset = 0;
|
10 | }
|
11 |
|
12 | async addAsset(asset) {
|
13 | let css = asset.generated.css || '';
|
14 |
|
15 |
|
16 |
|
17 | let media = [];
|
18 | for (let dep of asset.parentDeps) {
|
19 | if (!dep.media) {
|
20 |
|
21 | media.length = 0;
|
22 | break;
|
23 | } else {
|
24 | media.push(dep.media);
|
25 | }
|
26 | }
|
27 |
|
28 |
|
29 | if (media.length) {
|
30 | css = `@media ${media.join(', ')} {\n${css.trim()}\n}\n`;
|
31 | }
|
32 |
|
33 | if (asset.options.sourceMaps) {
|
34 | let lineCount = lineCounter(css);
|
35 |
|
36 | if (lineCount == 1) {
|
37 | this.bundle.addOffset(asset, this.lineOffset, this.columnOffset);
|
38 | await this.write(css);
|
39 | this.columnOffset += css.length;
|
40 | } else {
|
41 | const lines = css.split('\n');
|
42 | if (this.columnOffset == 0) {
|
43 | this.bundle.addOffset(asset, this.lineOffset, 0);
|
44 | await this.write(css + '\n');
|
45 | } else {
|
46 | this.columnOffset = 0;
|
47 | this.bundle.addOffset(asset, this.lineOffset + 1, 0);
|
48 | this.columnOffset = lines[lines.length - 1].length;
|
49 | await this.write('\n' + css);
|
50 | }
|
51 | this.lineOffset += lineCount;
|
52 | }
|
53 | } else {
|
54 | await this.write(css);
|
55 | }
|
56 | }
|
57 |
|
58 | async end() {
|
59 | if (this.options.sourceMaps) {
|
60 |
|
61 | let mapBundle = this.bundle.siblingBundlesMap.get('map');
|
62 | if (mapBundle) {
|
63 | let mapUrl = urlJoin(
|
64 | this.options.publicURL,
|
65 | path.basename(mapBundle.name)
|
66 | );
|
67 | await this.write(`\n/*# sourceMappingURL=${mapUrl} */`);
|
68 | }
|
69 | }
|
70 | await super.end();
|
71 | }
|
72 | }
|
73 |
|
74 | module.exports = CSSPackager;
|