-
Notifications
You must be signed in to change notification settings - Fork 360
/
index.js
613 lines (552 loc) · 15.7 KB
/
index.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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
import fs from 'fs';
import { resolve, relative, dirname, basename, extname } from 'path';
import chalk from 'chalk';
import { map, series } from 'asyncro';
import glob from 'tiny-glob/sync';
import autoprefixer from 'autoprefixer';
import cssnano from 'cssnano';
import { rollup, watch } from 'rollup';
import commonjs from 'rollup-plugin-commonjs';
import babel from 'rollup-plugin-babel';
import nodeResolve from 'rollup-plugin-node-resolve';
import buble from 'rollup-plugin-buble';
import { terser } from 'rollup-plugin-terser';
import alias from 'rollup-plugin-alias';
import postcss from 'rollup-plugin-postcss';
import gzipSize from 'gzip-size';
import brotliSize from 'brotli-size';
import prettyBytes from 'pretty-bytes';
import shebangPlugin from 'rollup-plugin-preserve-shebang';
import typescript from 'rollup-plugin-typescript2';
import json from 'rollup-plugin-json';
import flow from './lib/flow-plugin';
import logError from './log-error';
import { readFile, isDir, isFile, stdout, stderr } from './utils';
import camelCase from 'camelcase';
const removeScope = name => name.replace(/^@.*\//, '');
// Convert booleans and int define= values to literals.
// This is more intuitive than `microbundle --define A=1` producing A="1".
// See: https://github.com/terser-js/terser#conditional-compilation-api
const toTerserLiteral = (value, name) => {
// --define A="1",B='true' produces string:
const matches = value.match(/^(['"])(.+)\1$/);
if (matches) {
return [matches[2], name];
}
// --define A=1,B=true produces int/boolean literal:
if (/^(true|false|\d+)$/i.test(value)) {
return [value, '@' + name];
}
// default: behaviour from Terser (@prefix=1 produces expression/literal, unprefixed=1 produces string literal):
};
// Parses values of the form "$=jQuery,React=react" into key-value object pairs.
const parseMappingArgument = (globalStrings, processValue) => {
const globals = {};
globalStrings.split(',').forEach(globalString => {
let [key, value] = globalString.split('=');
if (processValue) {
const r = processValue(value, key);
if (r !== undefined) {
if (Array.isArray(r)) {
[value, key] = r;
} else {
value = r;
}
}
}
globals[key] = value;
});
return globals;
};
// Extensions to use when resolving modules
const EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx', '.es6', '.es', '.mjs'];
const WATCH_OPTS = {
exclude: 'node_modules/**',
};
// Hoist function because something (rollup?) incorrectly removes it
function formatSize(size, filename, type, raw) {
const pretty = raw ? `${size} B` : prettyBytes(size);
const color = size < 5000 ? 'green' : size > 40000 ? 'red' : 'yellow';
const MAGIC_INDENTATION = type === 'br' ? 13 : 10;
return `${' '.repeat(MAGIC_INDENTATION - pretty.length)}${chalk[color](
pretty,
)}: ${chalk.white(basename(filename))}.${type}`;
}
export default async function microbundle(inputOptions) {
let options = { ...inputOptions };
options.cwd = resolve(process.cwd(), inputOptions.cwd);
const cwd = options.cwd;
const { hasPackageJson, pkg } = await getConfigFromPkgJson(cwd);
options.pkg = pkg;
const { finalName, pkgName } = getName({
name: options.name,
pkgName: options.pkg.name,
amdName: options.pkg.amdName,
hasPackageJson,
cwd,
});
options.name = finalName;
options.pkg.name = pkgName;
if (options.sourcemap !== false) {
options.sourcemap = true;
}
options.input = await getInput({
entries: options.entries,
cwd,
source: options.pkg.source,
module: options.pkg.module,
});
options.output = await getOutput({
cwd,
output: options.output,
pkgMain: options.pkg.main,
pkgName: options.pkg.name,
});
options.entries = await getEntries({
cwd,
input: options.input,
});
options.multipleEntries = options.entries.length > 1;
let formats = (options.format || options.formats).split(',');
// always compile cjs first if it's there:
formats.sort((a, b) => (a === 'cjs' ? -1 : a > b ? 1 : 0));
let steps = [];
for (let i = 0; i < options.entries.length; i++) {
for (let j = 0; j < formats.length; j++) {
steps.push(
createConfig(
options,
options.entries[i],
formats[j],
i === 0 && j === 0,
),
);
}
}
async function getSizeInfo(code, filename) {
const raw = options.raw || code.length < 5000;
const gzip = formatSize(await gzipSize(code), filename, 'gz', raw);
const brotli = formatSize(await brotliSize(code), filename, 'br', raw);
return gzip + '\n' + brotli;
}
if (options.watch) {
const onBuild = options.onBuild;
return new Promise((resolve, reject) => {
stdout(
chalk.blue(
`Watching source, compiling to ${relative(
cwd,
dirname(options.output),
)}:`,
),
);
steps.map(options => {
watch(
Object.assign(
{
output: options.outputOptions,
watch: WATCH_OPTS,
},
options.inputOptions,
),
).on('event', e => {
if (e.code === 'FATAL') {
return reject(e.error);
} else if (e.code === 'ERROR') {
logError(e.error);
}
if (e.code === 'END') {
getSizeInfo(options._code, options.outputOptions.file).then(
text => {
stdout(`Wrote ${text.trim()}`);
},
);
if (typeof onBuild === 'function') {
onBuild(e);
}
}
});
});
});
}
let cache;
let out = await series(
steps.map(({ inputOptions, outputOptions }) => async () => {
inputOptions.cache = cache;
let bundle = await rollup(inputOptions);
cache = bundle;
const { code } = await bundle.write(outputOptions);
return await getSizeInfo(code, outputOptions.file);
}),
);
return (
chalk.blue(
`Build "${options.name}" to ${relative(cwd, dirname(options.output)) ||
'.'}:`,
) +
'\n ' +
out.join('\n ')
);
}
async function getConfigFromPkgJson(cwd) {
try {
const pkgJSON = await readFile(resolve(cwd, 'package.json'), 'utf8');
const pkg = JSON.parse(pkgJSON);
return {
hasPackageJson: true,
pkg,
};
} catch (err) {
const pkgName = basename(cwd);
stderr(
chalk.yellow(
`${chalk.yellow.inverse(
'WARN',
)} no package.json found. Assuming a pkg.name of "${pkgName}".`,
),
);
let msg = String(err.message || err);
if (!msg.match(/ENOENT/)) stderr(` ${chalk.red.dim(msg)}`);
return { hasPackageJson: false, pkg: { name: pkgName } };
}
}
const safeVariableName = name =>
camelCase(
removeScope(name)
.toLowerCase()
.replace(/((^[^a-zA-Z]+)|[^\w.-])|([^a-zA-Z0-9]+$)/g, ''),
);
function getName({ name, pkgName, amdName, cwd, hasPackageJson }) {
if (!pkgName) {
pkgName = basename(cwd);
if (hasPackageJson) {
stderr(
chalk.yellow(
`${chalk.yellow.inverse(
'WARN',
)} missing package.json "name" field. Assuming "${pkgName}".`,
),
);
}
}
return { finalName: name || amdName || safeVariableName(pkgName), pkgName };
}
async function jsOrTs(cwd, filename) {
const extension = (await isFile(resolve(cwd, filename + '.ts')))
? '.ts'
: (await isFile(resolve(cwd, filename + '.tsx')))
? '.tsx'
: '.js';
return resolve(cwd, `${filename}${extension}`);
}
async function getInput({ entries, cwd, source, module }) {
const input = [];
[]
.concat(
entries && entries.length
? entries
: (source && resolve(cwd, source)) ||
((await isDir(resolve(cwd, 'src'))) &&
(await jsOrTs(cwd, 'src/index'))) ||
(await jsOrTs(cwd, 'index')) ||
module,
)
.map(file => glob(file))
.forEach(file => input.push(...file));
return input;
}
async function getOutput({ cwd, output, pkgMain, pkgName }) {
let main = resolve(cwd, output || pkgMain || 'dist');
if (!main.match(/\.[a-z]+$/) || (await isDir(main))) {
main = resolve(main, `${removeScope(pkgName)}.js`);
}
return main;
}
async function getEntries({ input, cwd }) {
let entries = (await map([].concat(input), async file => {
file = resolve(cwd, file);
if (await isDir(file)) {
file = resolve(file, 'index.js');
}
return file;
})).filter((item, i, arr) => arr.indexOf(item) === i);
return entries;
}
function createConfig(options, entry, format, writeMeta) {
let { pkg } = options;
let external = ['dns', 'fs', 'path', 'url'].concat(
options.entries.filter(e => e !== entry),
);
let outputAliases = {};
// since we transform src/index.js, we need to rename imports for it:
if (options.multipleEntries) {
outputAliases['.'] = './' + basename(options.output);
}
const moduleAliases = options.alias
? parseMappingArgument(options.alias)
: {};
const peerDeps = Object.keys(pkg.peerDependencies || {});
if (options.external === 'none') {
// bundle everything (external=[])
} else if (options.external) {
external = external.concat(peerDeps).concat(options.external.split(','));
} else {
external = external
.concat(peerDeps)
.concat(Object.keys(pkg.dependencies || {}));
}
let globals = external.reduce((globals, name) => {
// valid JS identifiers are usually library globals:
if (name.match(/^[a-z_$][a-z0-9_$]*$/)) {
globals[name] = name;
}
return globals;
}, {});
if (options.globals && options.globals !== 'none') {
globals = Object.assign(globals, parseMappingArgument(options.globals));
}
let defines = {};
if (options.define) {
defines = Object.assign(
defines,
parseMappingArgument(options.define, toTerserLiteral),
);
}
function replaceName(filename, name) {
return resolve(
dirname(filename),
name + basename(filename).replace(/^[^.]+/, ''),
);
}
let mainNoExtension = options.output;
if (options.multipleEntries) {
let name = entry.match(/([\\/])index(\.(umd|cjs|es|m))?\.m?js$/)
? mainNoExtension
: entry;
mainNoExtension = resolve(dirname(mainNoExtension), basename(name));
}
mainNoExtension = mainNoExtension.replace(/(\.(umd|cjs|es|m))?\.m?js$/, '');
let moduleMain = replaceName(
pkg.module && !pkg.module.match(/src\//)
? pkg.module
: pkg['jsnext:main'] || 'x.mjs',
mainNoExtension,
);
let cjsMain = replaceName(pkg['cjs:main'] || 'x.js', mainNoExtension);
let umdMain = replaceName(pkg['umd:main'] || 'x.umd.js', mainNoExtension);
// let rollupName = safeVariableName(basename(entry).replace(/\.js$/, ''));
let nameCache = {};
let mangleOptions = options.pkg.mangle || false;
const useTypescript = extname(entry) === '.ts' || extname(entry) === '.tsx';
const externalPredicate = new RegExp(`^(${external.join('|')})($|/)`);
const externalTest =
external.length === 0 ? () => false : id => externalPredicate.test(id);
function loadNameCache() {
try {
nameCache = JSON.parse(
fs.readFileSync(resolve(options.cwd, 'mangle.json'), 'utf8'),
);
if (nameCache.config) {
mangleOptions = Object.assign({}, mangleOptions || {}, nameCache.config);
}
} catch (e) {}
}
loadNameCache();
let shebang;
let config = {
inputOptions: {
input: entry,
external: id => {
if (id === 'babel-plugin-transform-async-to-promises/helpers') {
return false;
}
if (options.multipleEntries && id === '.') {
return true;
}
return externalTest(id);
},
treeshake: {
propertyReadSideEffects: false,
},
plugins: []
.concat(
postcss({
plugins: [
autoprefixer(),
options.compress !== false &&
cssnano({
preset: 'default',
}),
].filter(Boolean),
// only write out CSS for the first bundle (avoids pointless extra files):
inject: false,
extract: !!writeMeta,
}),
Object.keys(moduleAliases).length > 0 &&
alias(
Object.assign({}, moduleAliases, {
resolve: EXTENSIONS,
}),
),
nodeResolve({
module: true,
jsnext: true,
browser: options.target !== 'node',
}),
commonjs({
// use a regex to make sure to include eventual hoisted packages
include: /\/node_modules\//,
}),
json(),
useTypescript &&
typescript({
typescript: require('typescript'),
cacheRoot: `./.rts2_cache_${format}`,
tsconfigDefaults: {
compilerOptions: {
sourceMap: options.sourcemap,
declaration: true,
jsx: options.jsx,
},
},
tsconfigOverride: {
compilerOptions: {
target: 'esnext',
},
},
}),
!useTypescript && flow({ all: true, pretty: true }),
// Only used for async await
babel({
// We mainly use bublé to transpile JS and only use babel to
// transpile down `async/await`. To prevent conflicts with user
// supplied configurations we set this option to false. Note
// that we never supported using custom babel configs anyway.
babelrc: false,
extensions: EXTENSIONS,
exclude: 'node_modules/**',
plugins: [
require.resolve('@babel/plugin-syntax-jsx'),
[
require.resolve('babel-plugin-transform-async-to-promises'),
{ inlineHelpers: true, externalHelpers: true },
],
[
require.resolve('@babel/plugin-proposal-class-properties'),
{ loose: true },
],
],
}),
{
// Custom plugin that removes shebang from code because newer
// versions of bublé bundle their own private version of `acorn`
// and I don't know a way to patch in the option `allowHashBang`
// to acorn.
// See: https://github.com/Rich-Harris/buble/pull/165
transform(code) {
let reg = /^#!(.*)/;
let match = code.match(reg);
if (match !== null) {
shebang = '#!' + match[0];
}
code = code.replace(reg, '');
return {
code,
map: null,
};
},
},
buble({
exclude: 'node_modules/**',
jsx: options.jsx || 'h',
objectAssign: options.assign || 'Object.assign',
transforms: {
dangerousForOf: true,
dangerousTaggedTemplateString: true,
},
}),
// We should upstream this to rollup
// format==='cjs' && replace({
// [`module.exports = ${rollupName};`]: '',
// [`var ${rollupName} =`]: 'module.exports ='
// }),
// This works for the general case, but could cause nasty scope bugs.
// format==='umd' && replace({
// [`return ${rollupName};`]: '',
// [`var ${rollupName} =`]: 'return'
// }),
// format==='es' && replace({
// [`export default ${rollupName};`]: '',
// [`var ${rollupName} =`]: 'export default'
// }),
options.compress !== false && [
terser({
sourcemap: true,
output: { comments: false },
compress: Object.assign({
keep_infinity: true,
pure_getters: true,
global_defs: defines,
passes: 10,
}, mangleOptions.compress || {}),
warnings: true,
ecma: 5,
toplevel: format === 'cjs' || format === 'es',
mangle: Object.assign({
properties: mangleOptions
? {
regex: mangleOptions.regex
? new RegExp(mangleOptions.regex)
: null,
reserved: mangleOptions.reserved || [],
}
: false,
}, mangleOptions.mangle || {}),
nameCache,
}),
mangleOptions && {
// before hook
options: loadNameCache,
// after hook
onwrite() {
if (writeMeta && nameCache) {
fs.writeFile(
resolve(options.cwd, 'mangle.json'),
JSON.stringify(nameCache, null, 2),
Object,
);
}
},
},
],
{
ongenerate(outputOptions, { code }) {
config._code = code;
},
},
shebangPlugin({
shebang,
}),
)
.filter(Boolean),
},
outputOptions: {
paths: outputAliases,
globals,
strict: options.strict === true,
legacy: true,
freeze: false,
esModule: false,
sourcemap: options.sourcemap,
format,
name: options.name,
file: resolve(
options.cwd,
(format === 'es' && moduleMain) ||
(format === 'umd' && umdMain) ||
cjsMain,
),
},
};
return config;
}