-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathrollup.config.js
504 lines (428 loc) · 18.4 KB
/
rollup.config.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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
/* eslint-disable max-depth, no-loop-func */
const Buffer = require('buffer').Buffer;
const fs = require('fs');
const htmlparser = require('node-html-parser');
const json = require('@rollup/plugin-json');
const multiInput = require('rollup-plugin-multi-input').default;
const { nodeResolve } = require('@rollup/plugin-node-resolve');
const path = require('path');
const postcss = require('postcss');
const postcssImport = require('postcss-import');
const replace = require('@rollup/plugin-replace');
const { terser } = require('rollup-plugin-terser');
const tokenSuffix = 'scratch';
const tokenNodeModules = 'node_modules/';
const parseTagForAttributes = (tag) => {
return tag.rawAttrs.split(' ').map((attribute) => {
if (attribute.indexOf('=') > 0) {
const attributePieces = attribute.split('=');
return {
[attributePieces[0]]: attributePieces[1].replace(/"/g, '').replace(/'/g, '')
};
} else {
return undefined;
}
}).filter(attribute => attribute)
.reduce((accum, attribute) => {
return Object.assign(accum, {
...attribute
});
}, {});
};
async function getOptimizedSource(url, plugins, compilation) {
const initSoure = fs.readFileSync(url, 'utf-8');
let optimizedSource = await plugins.reduce(async (bodyPromise, resource) => {
const body = await bodyPromise;
const shouldOptimize = await resource.shouldOptimize(url, body);
if (shouldOptimize) {
const optimizedBody = await resource.optimize(url, body);
return Promise.resolve(optimizedBody);
} else {
return Promise.resolve(body);
}
}, Promise.resolve(initSoure));
// if no custom user optimization found, fallback to standard Greenwood default optimization
if (optimizedSource === initSoure) {
const standardPluginsPath = path.join(__dirname, '../', 'plugins/resource');
const standardPlugins = (await fs.promises.readdir(standardPluginsPath))
.filter(filename => filename.indexOf('plugin-standard') === 0)
.map((filename) => {
return require(`${standardPluginsPath}/${filename}`);
}).map((plugin) => {
return plugin.provider(compilation);
});
optimizedSource = await standardPlugins.reduce(async (sourcePromise, resource) => {
const source = await sourcePromise;
const shouldOptimize = await resource.shouldOptimize(url, source);
if (shouldOptimize) {
const defaultOptimizedSource = await resource.optimize(url, source);
return Promise.resolve(defaultOptimizedSource);
} else {
return Promise.resolve(source);
}
}, Promise.resolve(optimizedSource));
}
return Promise.resolve(optimizedSource);
}
function greenwoodWorkspaceResolver (compilation) {
const { userWorkspace, scratchDir } = compilation.context;
return {
name: 'greenwood-workspace-resolver',
resolveId(source) {
if ((source.indexOf('./') === 0 || source.indexOf('/') === 0) && path.extname(source) !== '.html' && fs.existsSync(path.join(userWorkspace, source))) {
return source.replace(source, path.join(userWorkspace, source));
}
// handle inline script / style bundling
if (source.indexOf(`-${tokenSuffix}`) > 0 && fs.existsSync(path.join(scratchDir, source))) {
return source.replace(source, path.join(scratchDir, source));
}
return null;
}
};
}
// https://github.com/rollup/rollup/issues/2873
function greenwoodHtmlPlugin(compilation) {
const { projectDirectory, userWorkspace, outputDir, scratchDir } = compilation.context;
const { optimization } = compilation.config;
const isRemoteUrl = (url = undefined) => url && (url.indexOf('http') === 0 || url.indexOf('//') === 0);
const customResources = compilation.config.plugins.filter((plugin) => {
return plugin.type === 'resource';
}).map((plugin) => {
return plugin.provider(compilation);
});
return {
name: 'greenwood-html-plugin',
// tell Rollup how to handle HTML entry points
// and other custom user resource types like .ts, .gql, etc
async load(id) {
const extension = path.extname(id);
switch (extension) {
case '.html':
return Promise.resolve('');
default:
const resourceHandler = (await Promise.all(customResources.map(async (resource) => {
const shouldServe = await resource.shouldServe(id);
return shouldServe
? resource
: null;
}))).filter(resource => resource);
if (resourceHandler.length) {
const response = await resourceHandler[0].serve(id);
return Promise.resolve(response.body);
}
break;
}
},
// crawl through all entry HTML files and emit JavaScript chunks and CSS assets along the way
// for bundling with Rollup
buildStart(options) {
const mappedStyles = [];
const mappedScripts = new Map();
for (const input in options.input) {
try {
const inputHtml = options.input[input];
const html = fs.readFileSync(inputHtml, 'utf-8');
const root = htmlparser.parse(html, {
script: true,
style: true
});
const headScripts = root.querySelectorAll('script');
const headLinks = root.querySelectorAll('link');
headScripts.forEach((scriptTag) => {
const parsedAttributes = parseTagForAttributes(scriptTag);
// handle <script type="module" src="some/path.js"></script>
if (!isRemoteUrl(parsedAttributes.src) && parsedAttributes.type === 'module' && parsedAttributes.src && !mappedScripts.get(parsedAttributes.src)) {
if (optimization === 'static') {
// console.debug('dont emit ', parsedAttributes.src);
} else {
const { src } = parsedAttributes;
mappedScripts.set(src, true);
const srcPath = src.replace('../', './');
const basePath = srcPath.indexOf(tokenNodeModules) >= 0
? projectDirectory
: userWorkspace;
const source = fs.readFileSync(path.join(basePath, srcPath), 'utf-8');
this.emitFile({
type: 'chunk',
id: srcPath.replace('/node_modules', path.join(projectDirectory, tokenNodeModules)),
name: srcPath.split('/')[srcPath.split('/').length - 1].replace('.js', ''),
source
});
}
}
// handle <script type="module">/* some inline JavaScript code */</script>
if (parsedAttributes.type === 'module' && scriptTag.rawText !== '') {
const id = Buffer.from(scriptTag.rawText).toString('base64').slice(0, 8).toLowerCase();
if (!mappedScripts.get(id)) {
const filename = `${id}-${tokenSuffix}.js`;
const source = `
// ${filename}
${scriptTag.rawText}
`.trim();
fs.writeFileSync(path.join(scratchDir, filename), source);
mappedScripts.set(id, true);
this.emitFile({
type: 'chunk',
id: filename,
name: filename.replace('.js', ''),
source
});
}
}
});
headLinks.forEach((linkTag) => {
const parsedAttributes = parseTagForAttributes(linkTag);
// handle <link rel="stylesheet" src="./some/path.css"></link>
if (!isRemoteUrl(parsedAttributes.href) && parsedAttributes.rel === 'stylesheet' && !mappedStyles[parsedAttributes.href]) {
let { href } = parsedAttributes;
if (href.charAt(0) === '/') {
href = href.slice(1);
}
const basePath = href.indexOf(tokenNodeModules) >= 0
? projectDirectory
: userWorkspace;
const filePath = path.join(basePath, href.replace('../', './'));
const source = fs.readFileSync(filePath, 'utf-8');
const to = `${outputDir}/${href}`;
const hash = Buffer.from(source).toString('base64').toLowerCase();
const fileName = href
.replace('.css', `.${hash.slice(0, 8)}.css`)
.replace('../', '')
.replace('./', '');
if (!fs.existsSync(path.dirname(to)) && href.indexOf(tokenNodeModules) < 0) {
fs.mkdirSync(path.dirname(to), {
recursive: true
});
}
mappedStyles[parsedAttributes.href] = {
type: 'asset',
fileName: fileName.indexOf(tokenNodeModules) >= 0
? path.basename(fileName)
: fileName,
name: href,
source
};
}
});
} catch (e) {
console.error(e);
}
}
// this is a giant work around because PostCSS and some plugins can only be run async
// and so have to use with await but _outside_ sync code, like parser / rollup
// https://github.com/cssnano/cssnano/issues/68
// https://github.com/postcss/postcss/issues/595
Promise.all(Object.keys(mappedStyles).map(async (assetKey) => {
const asset = mappedStyles[assetKey];
const source = mappedStyles[assetKey].source;
const basePath = asset.name.indexOf(tokenNodeModules) >= 0
? projectDirectory
: userWorkspace;
const result = await postcss()
.use(postcssImport())
.process(source, {
from: path.join(basePath, asset.name)
});
asset.source = result.css;
return new Promise((resolve, reject) => {
try {
this.emitFile(asset);
resolve();
} catch (e) {
reject(e);
}
});
}));
},
// crawl through all entry HTML files and map bundled JavaScript and CSS filenames
// back to original <script> / <link> tags and update to their bundled filename in the HTML
generateBundle(outputOptions, bundles) {
for (const bundleId of Object.keys(bundles)) {
try {
const bundle = bundles[bundleId];
if (bundle.isEntry && path.extname(bundle.facadeModuleId) === '.html') {
const html = fs.readFileSync(bundle.facadeModuleId, 'utf-8');
const root = htmlparser.parse(html, {
script: true,
style: true
});
const headScripts = root.querySelectorAll('script');
const headLinks = root.querySelectorAll('link');
let newHtml = html;
headScripts.forEach((scriptTag) => {
const parsedAttributes = parseTagForAttributes(scriptTag);
// handle <script type="module" src="some/path.js"></script>
if (!isRemoteUrl(parsedAttributes.src) && parsedAttributes.type === 'module' && parsedAttributes.src) {
for (const innerBundleId of Object.keys(bundles)) {
const { src } = parsedAttributes;
const facadeModuleId = bundles[innerBundleId].facadeModuleId;
let pathToMatch = src.replace('../', '').replace('./', '');
// special handling for node_modules paths
if (pathToMatch.indexOf(tokenNodeModules) >= 0) {
pathToMatch = pathToMatch.replace(`/${tokenNodeModules}`, '');
const pathToMatchPieces = pathToMatch.split('/');
pathToMatch = pathToMatch.replace(tokenNodeModules, '');
pathToMatch = pathToMatch.replace(`${pathToMatchPieces[0]}/`, '');
}
if (facadeModuleId && facadeModuleId.indexOf(pathToMatch) > 0) {
const newSrc = `/${innerBundleId}`;
newHtml = newHtml.replace(src, newSrc);
if (optimization !== 'none' && optimization !== 'inline') {
newHtml = newHtml.replace('<head>', `
<head>
<link rel="modulepreload" href="${newSrc}" as="script">
`);
}
} else if (optimization === 'static' && newHtml.indexOf(pathToMatch) > 0) {
newHtml = newHtml.replace(scriptTag, '');
}
}
}
});
headLinks.forEach((linkTag) => {
const parsedAttributes = parseTagForAttributes(linkTag);
const { href } = parsedAttributes;
// handle <link rel="stylesheet" src="/some/path.css"></link>
if (parsedAttributes.rel === 'stylesheet') {
for (const bundleId2 of Object.keys(bundles)) {
if (bundleId2.indexOf('.css') > 0) {
const bundle2 = bundles[bundleId2];
if (href.indexOf(bundle2.name) >= 0) {
const newHref = `/${bundle2.fileName}`;
newHtml = newHtml.replace(href, newHref);
if (optimization !== 'none' && optimization !== 'inline') {
newHtml = newHtml.replace('<head>', `
<head>
<link rel="preload" href="${newHref}" as="style" crossorigin="anonymous"></link>
`);
}
}
}
}
}
});
bundle.fileName = bundle.facadeModuleId.replace('.greenwood', 'public');
bundle.code = newHtml;
}
} catch (e) {
console.error('ERROR', e);
}
}
},
async writeBundle(outputOptions, bundles) {
const scratchFiles = {};
for (const bundleId of Object.keys(bundles)) {
const bundle = bundles[bundleId];
if (bundle.isEntry && path.extname(bundle.facadeModuleId) === '.html') {
const htmlPath = bundle.facadeModuleId.replace('.greenwood', 'public');
let html = fs.readFileSync(htmlPath, 'utf-8');
const root = htmlparser.parse(html, {
script: true,
style: true
});
const headScripts = root.querySelectorAll('script');
const headLinks = root.querySelectorAll('link');
headScripts.forEach((scriptTag) => {
const parsedAttributes = parseTagForAttributes(scriptTag);
const isScriptSrcTag = parsedAttributes.src && parsedAttributes.type === 'module';
if (optimization === 'inline' && isScriptSrcTag && !isRemoteUrl(parsedAttributes.src)) {
const src = parsedAttributes.src;
const basePath = src.indexOf(tokenNodeModules) >= 0
? process.cwd()
: outputDir;
const outputPath = path.join(basePath, src);
const js = fs.readFileSync(outputPath, 'utf-8');
// scratchFiles[src] = true;
html = html.replace(`<script ${scriptTag.rawAttrs}></script>`, `
<script type="module">
${js}
</script>
`);
}
// handle <script type="module"> /* inline code */ </script>
if (parsedAttributes.type === 'module' && !parsedAttributes.src) {
for (const innerBundleId of Object.keys(bundles)) {
if (innerBundleId.indexOf(`-${tokenSuffix}`) > 0 && path.extname(innerBundleId) === '.js') {
const bundledSource = fs.readFileSync(path.join(outputDir, innerBundleId), 'utf-8')
.replace(/\.\//g, '/'); // force absolute paths
html = html.replace(scriptTag.rawText, bundledSource);
scratchFiles[innerBundleId] = true;
}
}
}
});
if (optimization === 'inline') {
headLinks
.forEach((linkTag) => {
const linkTagAttributes = parseTagForAttributes(linkTag);
const isLocalLinkTag = linkTagAttributes.rel === 'stylesheet'
&& !isRemoteUrl(linkTagAttributes.href);
if (isLocalLinkTag) {
const href = linkTagAttributes.href;
const outputPath = path.join(outputDir, href);
const css = fs.readFileSync(outputPath, 'utf-8');
// scratchFiles[href] = true;
html = html.replace(`<link ${linkTag.rawAttrs}>`, `
<style>
${css}
</style>
`);
}
});
}
await fs.promises.writeFile(htmlPath, html);
} else {
const sourcePath = `${outputDir}/${bundleId}`;
const optimizedSource = await getOptimizedSource(sourcePath, customResources, compilation);
await fs.promises.writeFile(sourcePath, optimizedSource);
}
}
// cleanup any scratch files
return Promise.all(Object.keys(scratchFiles).map(async (file) => {
return await fs.promises.unlink(path.join(outputDir, file));
}));
}
};
}
module.exports = getRollupConfig = async (compilation) => {
const { scratchDir, outputDir } = compilation.context;
const defaultRollupPlugins = [
replace({ // https://github.com/rollup/rollup/issues/487#issuecomment-177596512
'process.env.NODE_ENV': JSON.stringify('production')
}),
nodeResolve(),
greenwoodWorkspaceResolver(compilation),
greenwoodHtmlPlugin(compilation),
multiInput(),
json()
];
const customRollupPlugins = compilation.config.plugins.filter((plugin) => {
return plugin.type === 'rollup';
}).map((plugin) => {
return plugin.provider(compilation);
}).flat();
if (compilation.config.optimization !== 'none') {
defaultRollupPlugins.push(
terser()
);
}
return [{
input: `${scratchDir}**/*.html`,
output: {
dir: outputDir,
entryFileNames: '[name].[hash].js',
chunkFileNames: '[name].[hash].js'
},
onwarn: (messageObj) => {
if ((/EMPTY_BUNDLE/).test(messageObj.code)) {
return;
} else {
console.debug(messageObj.message);
}
},
plugins: [
...defaultRollupPlugins,
...customRollupPlugins
]
}];
};