/
rollup.js
271 lines (211 loc) · 8.72 KB
/
rollup.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
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
/* eslint max-statements: [ 1, 20 ] */
"use strict";
const path = require("path");
const { keyword } = require("esutils");
const utils = require("rollup-pluginutils");
const dedent = require("dedent");
const slash = require("slash");
const Processor = require("@modular-css/processor");
const output = require("@modular-css/processor/lib/output.js");
// sourcemaps for css-to-js don't make much sense, so always return nothing
// https://github.com/rollup/rollup/wiki/Plugins#conventions
const emptyMappings = {
mappings : "",
};
const makeFile = (details) => {
const { entry } = details;
const name = path.basename(entry, path.extname(entry));
return Object.assign(details, {
base : path.join(path.dirname(entry), name),
name,
});
};
module.exports = function(opts) {
const options = Object.assign(Object.create(null), {
common : "common.css",
json : false,
include : "**/*.css",
namedExports : true,
styleExport : false,
dev : false,
verbose : false,
}, opts);
const filter = utils.createFilter(options.include, options.exclude);
const { styleExport, done, map, dev, verbose } = options;
// eslint-disable-next-line no-console, no-empty-function
const log = verbose ? console.log.bind(console, "[rollup]") : () => {};
if(typeof map === "undefined") {
// Sourcemaps don't make much sense in styleExport mode
// But default to true otherwise
options.map = !styleExport;
}
const processor = options.processor || new Processor(options);
return {
name : "@modular-css/rollup",
buildStart() {
log("build start");
// done lifecycle won't ever be called on per-component styles since
// it only happens at bundle compilation time
// Need to do this on buildStart so it has access to this.warn() o_O
if(styleExport && done) {
this.warn(
`Any plugins defined during the "done" lifecycle won't run when "styleExport" is set!`
);
}
},
watchChange(file) {
if(!processor.files[file]) {
return;
}
log("file changed", file);
processor.dependents(file).forEach((dep) =>
processor.remove(dep)
);
processor.remove(file);
},
async transform(code, id) {
if(!filter(id)) {
return null;
}
log("transform", id);
const { details, exports } = await processor.string(id, code);
const exported = output.join(exports);
const out = [
dev ? dedent(`
const data = ${JSON.stringify(exported)};
export default new Proxy(data, {
get(tgt, key) {
if(key in tgt) {
return tgt[key];
}
throw new ReferenceError(
key + " is not exported by " + ${JSON.stringify(
slash(path.relative(process.cwd(), id))
)}
);
}
})
`) :
`export default ${JSON.stringify(exported, null, 4)};`,
];
if(options.namedExports) {
Object.entries(exported).forEach(([ ident, value ]) => {
if(keyword.isReservedWordES6(ident) || !keyword.isIdentifierNameES6(ident)) {
this.warn(`Invalid JS identifier "${ident}", unable to export`);
return;
}
out.push(`export var ${ident} = ${JSON.stringify(value)};`);
});
}
if(options.styleExport) {
out.push(`export var styles = ${JSON.stringify(details.result.css)};`);
}
return {
code : out.join("\n"),
map : emptyMappings,
dependencies : processor.dependencies(id),
};
},
async generateBundle(outputOptions, bundles) {
// styleExport disables all output file generation
if(styleExport) {
return;
}
const usage = new Map();
const common = new Map();
const files = [];
const { assetFileNames = "" } = outputOptions;
let to;
if(!outputOptions.file && !outputOptions.dir) {
to = path.join(process.cwd(), assetFileNames);
} else {
to = path.join(
outputOptions.dir ? outputOptions.dir : path.dirname(outputOptions.file),
assetFileNames
);
}
// First pass is used to calculate JS usage of CSS dependencies
Object.entries(bundles).forEach(([ entry, bundle ]) => {
const file = makeFile({
entry,
css : new Set(),
});
const { modules } = bundle;
// Get CSS files being used by each entry point
const css = Object.keys(modules).filter(filter);
// Get dependency chains for each file
css.forEach((start) => {
const used = [
...processor.dependencies(start),
start,
];
used.forEach((dep) => {
file.css.add(dep);
if(!usage.has(dep)) {
usage.set(dep, new Set());
}
usage.get(dep).add(entry);
});
});
files.push(file);
});
if(files.length === 1) {
// Only one entry file means we only need one bundle.
files[0].css = new Set(processor.dependencies());
} else {
// Multiple bundles means ref-counting to find the shared deps
// Second pass removes any dependencies appearing in multiple bundles
files.forEach((file) => {
const { css } = file;
file.css = new Set([ ...css ].filter((dep) => {
if(usage.get(dep).size > 1) {
common.set(dep, true);
return false;
}
return true;
}));
});
// Add any other files that weren't part of a bundle to the common chunk
Object.keys(processor.files).forEach((file) => {
if(!usage.has(file)) {
common.set(file, true);
}
});
// Common chunk only emitted if necessary
if(common.size) {
files.push(makeFile({
entry : options.common,
css : new Set([ ...common.keys() ]),
}));
}
}
await Promise.all(
files
.filter(({ css }) => css.size)
.map(async ({ base, name, css }, idx) => {
const id = this.emitAsset(`${base}.css`);
log("css output", id);
const result = await processor.output({
to : to.replace(/\[(name|extname)\]/g, (match, field) =>
(field === "name" ? name : ".css")
),
files : [ ...css ],
});
this.setAssetSource(id, result.css);
// result.compositions always includes all the info, so it
// doesn't actually matter which result we use. First one seems reasonable!
if(options.json && idx === 0) {
const file = typeof options.json === "string" ? options.json : "exports.json";
log("json output", file);
this.emitAsset(file, JSON.stringify(result.compositions, null, 4));
}
if(result.map) {
const file = `${base}.css.map`;
log("map output", file);
this.emitAsset(file, result.map.toString());
}
})
);
},
};
};