-
Notifications
You must be signed in to change notification settings - Fork 19
/
rollup.js
355 lines (275 loc) · 11.8 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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
/* eslint-disable max-statements, complexity */
"use strict";
const fs = require("fs");
const path = require("path");
const { keyword } = require("esutils");
const utils = require("rollup-pluginutils");
const dedent = require("dedent");
const slash = require("slash");
const Graph = require("dependency-graph").DepGraph;
const Processor = require("@modular-css/processor");
const output = require("@modular-css/processor/lib/output.js");
const { parse } = require("./parser.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 : "",
};
module.exports = (opts) => {
const options = Object.assign(Object.create(null), {
common : "common",
json : false,
include : "**/*.css",
namedExports : true,
styleExport : false,
dev : false,
verbose : false,
}, opts);
const filter = utils.createFilter(options.include, options.exclude);
const {
common,
dev,
done,
map,
styleExport,
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);
// random values that need to be shared between hooks (ugh)
const maps = [];
let assetFileNames;
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.has(file)) {
return;
}
log("file changed", file);
// TODO: should the file be removed if it's gone?
processor.invalidate(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 relative = path.relative(processor.options.cwd, id);
const out = [
...processor.dependencies(id).map((dep) => `import ${JSON.stringify(dep)};`),
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(relative))}
);
}
})
`) :
`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(styleExport) {
out.push(`export var styles = ${JSON.stringify(details.result.css)};`);
}
processor.dependencies(id).forEach((dependency) => this.addWatchFile(dependency));
return {
code : out.join("\n"),
map : emptyMappings,
};
},
async generateBundle(outputOptions, chunks) {
// styleExport disables all output file generation
if(styleExport) {
return;
}
// Really wish rollup would provide this default...
assetFileNames = outputOptions.assetFileNames || "assets/[name]-[hash][extname]";
const {
chunkFileNames = "[name]-[hash].js",
entryFileNames = "[name].js",
} = outputOptions;
// Determine the correct to option for PostCSS by doing a bit of a dance
let to;
if(!outputOptions.file && !outputOptions.dir) {
to = path.join(processor.options.cwd, assetFileNames);
} else {
to = path.join(
outputOptions.dir ? outputOptions.dir : path.dirname(outputOptions.file),
assetFileNames
);
}
// Build chunk dependency graph so it can be walked in order later to
// Allow for outputting CSS alongside chunks as optimally as possible
const usage = new Graph();
Object.entries(chunks).forEach(([ entry, chunk ]) => {
const { imports, dynamicImports } = chunk;
usage.addNode(entry, true);
[ ...imports, ...dynamicImports ].forEach((dep) => {
// Need to filter out invalid deps, see rollup/rollup#2659
if(!dep) {
return;
}
usage.addNode(dep, true);
usage.addDependency(entry, dep);
});
});
// Output CSS chunks
const out = [];
// Keep track of files that are queued to be written
const queued = new Set();
usage.overallOrder().forEach((entry) => {
const { modules, name, fileName, isEntry } = chunks[entry];
const css = new Set();
// Get CSS files being used by this chunk
const styles = Object.keys(modules).filter((file) => processor.has(file));
// Get dependency chains for each css file & record them into the usage graph
styles.forEach((style) => {
processor
.dependencies(style)
.forEach((file) => css.add(file));
css.add(style);
});
const included = [ ...css ].filter((file) => !queued.has(file));
if(!included.length) {
return;
}
// Parse out the name part from the resulting filename,
// based on the module's template (either entry or chunk)
let dest;
const template = isEntry ? entryFileNames : chunkFileNames;
if(template.includes("[hash]")) {
const parts = parse(template, fileName);
dest = parts.name;
} else {
// Want to use source chunk name when code-splitting, otherwise match bundle name
dest = outputOptions.dir ? name : path.basename(entry, path.extname(entry));
}
out.push([
dest,
included,
]);
// Flag all the files that are queued for writing so they don't get double-output
css.forEach((file) => queued.add(file));
});
// Figure out if there were any CSS files that the JS didn't reference
const unused = [];
processor.dependencies().forEach((css) => {
if(queued.has(css)) {
return;
}
queued.add(css);
unused.push(css);
});
// Shove any unreferenced CSS files onto the beginning of the first chunk
if(unused.length) {
if(out.length) {
out[0][1].unshift(...unused);
} else {
out.push([
common,
unused
]);
}
}
// If assets are being hashed then the automatic annotation has to be disabled
// because it won't include the hashed value and will lead to badness
let mapOpt = map;
if(assetFileNames.includes("[hash]") && typeof mapOpt === "object") {
mapOpt = Object.assign(
Object.create(null),
mapOpt,
{ annotation : false }
);
}
for(const [ name, files ] of out) {
const id = this.emitAsset(`${name}.css`);
/* eslint-disable-next-line no-await-in-loop */
const result = await processor.output({
// Can't use this.getAssetFileName() here, because the source hasn't been set yet
// Have to do our best to come up with a valid final location though...
to : to.replace(/\[(name|extname)\]/g, (match, field) => (field === "name" ? name : ".css")),
map : mapOpt,
files,
});
log("css output", `${name}.css`);
this.setAssetSource(id, result.css);
// Maps can't be written out via the asset APIs becuase they shouldn't ever be hashed.
// They shouldn't be hashed because they simply follow the name of their parent .css asset.
// So push them onto an array and write them out in the writeBundle hook below
if(result.map) {
const file = this.getAssetFileName(id);
maps.push({
to,
file,
content : result.map
});
}
}
if(options.json) {
const dest = typeof options.json === "string" ? options.json : "exports.json";
log("json output", dest);
const compositions = await processor.compositions;
this.emitAsset(dest, JSON.stringify(compositions, null, 4));
}
},
writeBundle() {
if(!maps.length) {
return;
}
maps.forEach(({ to, file, content }) => {
// Make sure to use the rollup name as the base, otherwise it won't
// automatically handle duplicate names correctly
const target = file.replace(".css", ".css.map");
const dest = path.join(
path.dirname(to),
path.basename(target)
);
log("map output", target);
fs.writeFileSync(dest, content.toString(), "utf8");
if(!assetFileNames.includes("hash")) {
return;
}
// Re-add the correct annotations to the end of the source files
const css = path.join(
path.dirname(to),
path.basename(file)
);
const source = fs.readFileSync(css, "utf8");
fs.writeFileSync(css, `${source}\n/*# sourceMappingURL=${path.basename(target)} */`);
});
}
};
};