forked from facebook/react
-
Notifications
You must be signed in to change notification settings - Fork 1
/
build.js
522 lines (491 loc) · 14.2 KB
/
build.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
'use strict';
const rollup = require('rollup').rollup;
const babel = require('rollup-plugin-babel');
const commonjs = require('rollup-plugin-commonjs');
const alias = require('rollup-plugin-alias');
const uglify = require('rollup-plugin-uglify');
const replace = require('rollup-plugin-replace');
const chalk = require('chalk');
const escapeStringRegexp = require('escape-string-regexp');
const join = require('path').join;
const resolve = require('path').resolve;
const fs = require('fs');
const rimraf = require('rimraf');
const argv = require('minimist')(process.argv.slice(2));
const Modules = require('./modules');
const Bundles = require('./bundles');
const propertyMangleWhitelist = require('./mangle').propertyMangleWhitelist;
const sizes = require('./plugins/sizes-plugin');
const Stats = require('./stats');
const syncReactNative = require('./sync').syncReactNative;
const Packaging = require('./packaging');
const Header = require('./header');
const UMD_DEV = Bundles.bundleTypes.UMD_DEV;
const UMD_PROD = Bundles.bundleTypes.UMD_PROD;
const NODE_DEV = Bundles.bundleTypes.NODE_DEV;
const NODE_PROD = Bundles.bundleTypes.NODE_PROD;
const FB_DEV = Bundles.bundleTypes.FB_DEV;
const FB_PROD = Bundles.bundleTypes.FB_PROD;
const RN_DEV = Bundles.bundleTypes.RN_DEV;
const RN_PROD = Bundles.bundleTypes.RN_PROD;
const reactVersion = require('../../package.json').version;
const requestedBundleTypes = (argv.type || '')
.split(',')
.map(type => type.toUpperCase());
const requestedBundleNames = (argv._[0] || '')
.split(',')
.map(type => type.toLowerCase());
const syncFbsource = argv['sync-fbsource'];
// used for when we property mangle with uglify/gcc
const mangleRegex = new RegExp(
`^(?${propertyMangleWhitelist
.map(prop => `!${escapeStringRegexp(prop)}`)
.join('|')}$).*$`,
'g'
);
function getHeaderSanityCheck(bundleType, hasteName) {
switch (bundleType) {
case FB_DEV:
case FB_PROD:
case RN_DEV:
case RN_PROD:
let hasteFinalName = hasteName;
switch (bundleType) {
case FB_DEV:
case RN_DEV:
hasteFinalName += '-dev';
break;
case FB_PROD:
case RN_PROD:
hasteFinalName += '-prod';
break;
}
return hasteFinalName;
case UMD_DEV:
case UMD_PROD:
return reactVersion;
default:
return null;
}
}
function getBanner(bundleType, hasteName, filename) {
switch (bundleType) {
case FB_DEV:
case FB_PROD:
case RN_DEV:
case RN_PROD:
let hasteFinalName = hasteName;
switch (bundleType) {
case FB_DEV:
case RN_DEV:
hasteFinalName += '-dev';
break;
case FB_PROD:
case RN_PROD:
hasteFinalName += '-prod';
break;
}
const fbDevCode = `\n\n'use strict';\n\n` + `\nif (__DEV__) {\n`;
return Header.getProvidesHeader(hasteFinalName, bundleType, fbDevCode);
case UMD_DEV:
case UMD_PROD:
return Header.getUMDHeader(filename, reactVersion);
default:
return '';
}
}
function getFooter(bundleType) {
if (bundleType === FB_DEV) {
return '\n}\n';
}
return '';
}
function updateBabelConfig(babelOpts, bundleType) {
switch (bundleType) {
case UMD_DEV:
case UMD_PROD:
case NODE_DEV:
case NODE_PROD:
return Object.assign({}, babelOpts, {
plugins: babelOpts.plugins.concat([
// Use object-assign polyfill in open source
resolve('./scripts/babel/transform-object-assign-require'),
// Replace __DEV__ with process.env.NODE_ENV and minify invariant messages
require('../error-codes/dev-expression-with-codes'),
]),
});
default:
return babelOpts;
}
}
function handleRollupWarnings(warning) {
if (warning.code === 'UNRESOLVED_IMPORT') {
console.error(warning.message);
process.exit(1);
}
console.warn(warning.message || warning);
}
function updateBundleConfig(config, filename, format, bundleType, hasteName) {
return Object.assign({}, config, {
banner: getBanner(bundleType, hasteName, filename),
dest: Packaging.getPackageDestination(config, bundleType, filename),
footer: getFooter(bundleType),
format,
interop: false,
});
}
function setReactNativeUseFiberEnvVariable(useFiber) {
return {
'process.env.REACT_NATIVE_USE_FIBER': useFiber,
};
}
function stripEnvVariables(production) {
return {
__DEV__: production ? 'false' : 'true',
'process.env.NODE_ENV': production ? "'production'" : "'development'",
};
}
function getFormat(bundleType) {
switch (bundleType) {
case UMD_DEV:
case UMD_PROD:
return `umd`;
case NODE_DEV:
case NODE_PROD:
case FB_DEV:
case FB_PROD:
case RN_DEV:
case RN_PROD:
return `cjs`;
}
}
function getFilename(name, hasteName, bundleType) {
// we do this to replace / to -, for react-dom/server
name = name.replace('/', '-');
switch (bundleType) {
case UMD_DEV:
return `${name}.development.js`;
case UMD_PROD:
return `${name}.production.min.js`;
case NODE_DEV:
return `${name}.development.js`;
case NODE_PROD:
return `${name}.production.min.js`;
case FB_DEV:
case RN_DEV:
return `${hasteName}-dev.js`;
case FB_PROD:
case RN_PROD:
return `${hasteName}-prod.js`;
}
}
function uglifyConfig(configs) {
var mangle = configs.mangle;
var manglePropertiesOnProd = configs.manglePropertiesOnProd;
var preserveVersionHeader = configs.preserveVersionHeader;
var removeComments = configs.removeComments;
var headerSanityCheck = configs.headerSanityCheck;
return {
warnings: false,
compress: {
screw_ie8: true,
dead_code: true,
unused: true,
drop_debugger: true,
// we have a string literal <script> that we don't want to evaluate
// for FB prod bundles (where we disable mangling)
evaluate: mangle,
booleans: true,
// Our www inline transform combined with Jest resetModules is confused
// in some rare cases unless we keep all requires at the top:
hoist_funs: mangle,
},
output: {
beautify: !mangle,
comments(node, comment) {
if (preserveVersionHeader && comment.pos === 0 && comment.col === 0) {
// Keep the very first comment (the bundle header) in prod bundles.
if (
headerSanityCheck &&
comment.value.indexOf(headerSanityCheck) === -1
) {
// Sanity check: this doesn't look like the bundle header!
throw new Error(
'Expected the first comment to be the file header but got: ' +
comment.value
);
}
return true;
}
return !removeComments;
},
},
mangleProperties: mangle && manglePropertiesOnProd
? {
ignore_quoted: true,
regex: mangleRegex,
}
: false,
mangle: mangle
? {
toplevel: true,
screw_ie8: true,
}
: false,
};
}
function getCommonJsConfig(bundleType) {
switch (bundleType) {
case UMD_DEV:
case UMD_PROD:
case NODE_DEV:
case NODE_PROD:
return {};
case RN_DEV:
case RN_PROD:
return {
ignore: Modules.ignoreReactNativeModules(),
};
case FB_DEV:
case FB_PROD:
// Modules we don't want to inline in the bundle.
// Force them to stay as require()s in the output.
return {
ignore: Modules.ignoreFBModules(),
};
}
}
function getPlugins(
entry,
babelOpts,
paths,
filename,
bundleType,
hasteName,
isRenderer,
manglePropertiesOnProd,
useFiber,
modulesToStub
) {
const plugins = [
babel(updateBabelConfig(babelOpts, bundleType)),
alias(
Modules.getAliases(paths, bundleType, isRenderer, argv['extract-errors'])
),
];
const replaceModules = Modules.getDefaultReplaceModules(
bundleType,
modulesToStub
);
// We have to do this check because Rollup breaks on empty object.
// TODO: file an issue with rollup-plugin-replace.
if (Object.keys(replaceModules).length > 0) {
plugins.unshift(replace(replaceModules));
}
const headerSanityCheck = getHeaderSanityCheck(bundleType, hasteName);
switch (bundleType) {
case UMD_DEV:
case NODE_DEV:
case FB_DEV:
plugins.push(
replace(stripEnvVariables(false)),
// needs to happen after strip env
commonjs(getCommonJsConfig(bundleType))
);
break;
case UMD_PROD:
case NODE_PROD:
case FB_PROD:
plugins.push(
replace(stripEnvVariables(true)),
// needs to happen after strip env
commonjs(getCommonJsConfig(bundleType)),
uglify(
uglifyConfig({
mangle: bundleType !== FB_PROD,
manglePropertiesOnProd,
preserveVersionHeader: bundleType === UMD_PROD,
// leave comments in for source map debugging purposes
// they will be stripped as part of FB's build process
removeComments: bundleType !== FB_PROD,
headerSanityCheck,
})
)
);
break;
case RN_DEV:
case RN_PROD:
plugins.push(
replace(stripEnvVariables(bundleType === RN_PROD)),
replace(setReactNativeUseFiberEnvVariable(useFiber)),
// needs to happen after strip env
commonjs(getCommonJsConfig(bundleType)),
uglify(
uglifyConfig({
mangle: false,
manglePropertiesOnProd,
preserveVersionHeader: true,
removeComments: true,
headerSanityCheck,
})
)
);
break;
}
// this needs to come last or it doesn't report sizes correctly
plugins.push(
sizes({
getSize: (size, gzip) => {
const key = `${filename} (${bundleType})`;
Stats.currentBuildResults.bundleSizes[key] = {
size,
gzip,
};
},
})
);
return plugins;
}
function createBundle(bundle, bundleType) {
const shouldSkipBundleType = bundle.bundleTypes.indexOf(bundleType) === -1;
if (shouldSkipBundleType) {
return Promise.resolve();
}
if (requestedBundleTypes.length > 0) {
const isAskingForDifferentType = requestedBundleTypes.every(
requestedType => bundleType.indexOf(requestedType) === -1
);
if (isAskingForDifferentType) {
return Promise.resolve();
}
}
if (requestedBundleNames.length > 0) {
const isAskingForDifferentNames = requestedBundleNames.every(
requestedName => bundle.label.indexOf(requestedName) === -1
);
if (isAskingForDifferentNames) {
return Promise.resolve();
}
}
const filename = getFilename(bundle.name, bundle.hasteName, bundleType);
const logKey =
chalk.white.bold(filename) + chalk.dim(` (${bundleType.toLowerCase()})`);
const format = getFormat(bundleType);
const packageName = Packaging.getPackageName(bundle.name);
console.log(`${chalk.bgYellow.black(' STARTING ')} ${logKey}`);
return rollup({
entry: bundleType === FB_DEV || bundleType === FB_PROD
? bundle.fbEntry
: bundle.entry,
external: Modules.getExternalModules(
bundle.externals,
bundleType,
bundle.isRenderer
),
onwarn: handleRollupWarnings,
plugins: getPlugins(
bundle.entry,
bundle.babelOpts,
bundle.paths,
filename,
bundleType,
bundle.hasteName,
bundle.isRenderer,
bundle.manglePropertiesOnProd,
bundle.useFiber,
bundle.modulesToStub
),
})
.then(result =>
result.write(
updateBundleConfig(
bundle.config,
filename,
format,
bundleType,
bundle.hasteName
)
)
)
.then(() => Packaging.createNodePackage(bundleType, packageName, filename))
.then(() => {
console.log(`${chalk.bgGreen.black(' COMPLETE ')} ${logKey}\n`);
})
.catch(error => {
if (error.code) {
console.error(`\x1b[31m-- ${error.code} (${error.plugin}) --`);
console.error(error.message);
console.error(error.loc);
console.error(error.codeFrame);
} else {
console.error(error);
}
process.exit(1);
});
}
// clear the build directory
rimraf('build', () => {
// create a new build directory
fs.mkdirSync('build');
// create the packages folder for NODE+UMD bundles
fs.mkdirSync(join('build', 'packages'));
// create the dist folder for UMD bundles
fs.mkdirSync(join('build', 'dist'));
const tasks = [
Packaging.createFacebookWWWBuild,
Packaging.createReactNativeBuild,
];
for (const bundle of Bundles.bundles) {
tasks.push(
() => createBundle(bundle, UMD_DEV),
() => createBundle(bundle, UMD_PROD),
() => createBundle(bundle, NODE_DEV),
() => createBundle(bundle, NODE_PROD),
() => createBundle(bundle, FB_DEV),
() => createBundle(bundle, FB_PROD),
() => createBundle(bundle, RN_DEV),
() => createBundle(bundle, RN_PROD)
);
}
if (syncFbsource) {
tasks.push(() =>
syncReactNative(join('build', 'react-native'), syncFbsource)
);
}
// rather than run concurently, opt to run them serially
// this helps improve console/warning/error output
// and fixes a bunch of IO failures that sometimes occured
return runWaterfall(tasks)
.then(() => {
// output the results
console.log(Stats.printResults());
// save the results for next run
Stats.saveResults();
if (argv['extract-errors']) {
console.warn(
'\nWarning: this build was created with --extract-errors enabled.\n' +
'this will result in extremely slow builds and should only be\n' +
'used when the error map needs to be rebuilt.\n'
);
}
})
.catch(err => {
console.error(err);
process.exit(1);
});
});
function runWaterfall(promiseFactories) {
if (promiseFactories.length === 0) {
return Promise.resolve();
}
const head = promiseFactories[0];
const tail = promiseFactories.slice(1);
const nextPromiseFactory = head;
const nextPromise = nextPromiseFactory();
if (!nextPromise || typeof nextPromise.then !== 'function') {
throw new Error('runWaterfall() received something that is not a Promise.');
}
return nextPromise.then(() => {
return runWaterfall(tail);
});
}