build.js 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. 'use strict';
  2. // Do this as the first thing so that any code reading it knows the right env.
  3. process.env.BABEL_ENV = 'production';
  4. process.env.NODE_ENV = 'production';
  5. // Makes the script crash on unhandled rejections instead of silently
  6. // ignoring them. In the future, promise rejections that are not handled will
  7. // terminate the Node.js process with a non-zero exit code.
  8. process.on('unhandledRejection', err => {
  9. throw err;
  10. });
  11. // Ensure environment variables are read.
  12. require('../config/env');
  13. const path = require('path');
  14. const chalk = require('chalk');
  15. const fs = require('fs-extra');
  16. const webpack = require('webpack');
  17. const bfj = require('bfj');
  18. const config = require('../config/webpack.config.prod');
  19. const paths = require('../config/paths');
  20. const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
  21. const formatWebpackMessages = require('react-dev-utils/formatWebpackMessages');
  22. const printHostingInstructions = require('react-dev-utils/printHostingInstructions');
  23. const FileSizeReporter = require('react-dev-utils/FileSizeReporter');
  24. const printBuildError = require('react-dev-utils/printBuildError');
  25. const measureFileSizesBeforeBuild =
  26. FileSizeReporter.measureFileSizesBeforeBuild;
  27. const printFileSizesAfterBuild = FileSizeReporter.printFileSizesAfterBuild;
  28. const useYarn = fs.existsSync(paths.yarnLockFile);
  29. // These sizes are pretty large. We'll warn for bundles exceeding them.
  30. const WARN_AFTER_BUNDLE_GZIP_SIZE = 512 * 1024;
  31. const WARN_AFTER_CHUNK_GZIP_SIZE = 1024 * 1024;
  32. const isInteractive = process.stdout.isTTY;
  33. // Warn and crash if required files are missing
  34. if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
  35. process.exit(1);
  36. }
  37. // Process CLI arguments
  38. const argv = process.argv.slice(2);
  39. const writeStatsJson = argv.indexOf('--stats') !== -1;
  40. // We require that you explictly set browsers and do not fall back to
  41. // browserslist defaults.
  42. const { checkBrowsers } = require('react-dev-utils/browsersHelper');
  43. checkBrowsers(paths.appPath, isInteractive)
  44. .then(() => {
  45. // First, read the current file sizes in build directory.
  46. // This lets us display how much they changed later.
  47. return measureFileSizesBeforeBuild(paths.appBuild);
  48. })
  49. .then(previousFileSizes => {
  50. // Remove all content but keep the directory so that
  51. // if you're in it, you don't end up in Trash
  52. fs.emptyDirSync(paths.appBuild);
  53. // Merge with the public folder
  54. copyPublicFolder();
  55. // Start the webpack build
  56. return build(previousFileSizes);
  57. })
  58. .then(
  59. ({ stats, previousFileSizes, warnings }) => {
  60. if (warnings.length) {
  61. console.log(chalk.yellow('Compiled with warnings.\n'));
  62. console.log(warnings.join('\n\n'));
  63. console.log(
  64. '\nSearch for the ' +
  65. chalk.underline(chalk.yellow('keywords')) +
  66. ' to learn more about each warning.'
  67. );
  68. console.log(
  69. 'To ignore, add ' +
  70. chalk.cyan('// eslint-disable-next-line') +
  71. ' to the line before.\n'
  72. );
  73. } else {
  74. console.log(chalk.green('Compiled successfully.\n'));
  75. }
  76. console.log('File sizes after gzip:\n');
  77. printFileSizesAfterBuild(
  78. stats,
  79. previousFileSizes,
  80. paths.appBuild,
  81. WARN_AFTER_BUNDLE_GZIP_SIZE,
  82. WARN_AFTER_CHUNK_GZIP_SIZE
  83. );
  84. console.log();
  85. const appPackage = require(paths.appPackageJson);
  86. const publicUrl = paths.publicUrl;
  87. const publicPath = config.output.publicPath;
  88. const buildFolder = path.relative(process.cwd(), paths.appBuild);
  89. printHostingInstructions(
  90. appPackage,
  91. publicUrl,
  92. publicPath,
  93. buildFolder,
  94. useYarn
  95. );
  96. },
  97. err => {
  98. console.log(chalk.red('Failed to compile.\n'));
  99. printBuildError(err);
  100. process.exit(1);
  101. }
  102. )
  103. .catch(err => {
  104. if (err && err.message) {
  105. console.log(err.message);
  106. }
  107. process.exit(1);
  108. });
  109. // Create the production build and print the deployment instructions.
  110. function build(previousFileSizes) {
  111. console.log('Creating an optimized production build...');
  112. let compiler = webpack(config);
  113. return new Promise((resolve, reject) => {
  114. compiler.run((err, stats) => {
  115. let messages;
  116. if (err) {
  117. if (!err.message) {
  118. return reject(err);
  119. }
  120. messages = formatWebpackMessages({
  121. errors: [err.message],
  122. warnings: [],
  123. });
  124. } else {
  125. messages = formatWebpackMessages(
  126. stats.toJson({ all: false, warnings: true, errors: true })
  127. );
  128. }
  129. if (messages.errors.length) {
  130. // Only keep the first error. Others are often indicative
  131. // of the same problem, but confuse the reader with noise.
  132. if (messages.errors.length > 1) {
  133. messages.errors.length = 1;
  134. }
  135. return reject(new Error(messages.errors.join('\n\n')));
  136. }
  137. if (
  138. process.env.CI &&
  139. (typeof process.env.CI !== 'string' ||
  140. process.env.CI.toLowerCase() !== 'false') &&
  141. messages.warnings.length
  142. ) {
  143. console.log(
  144. chalk.yellow(
  145. '\nTreating warnings as errors because process.env.CI = true.\n' +
  146. 'Most CI servers set it automatically.\n'
  147. )
  148. );
  149. return reject(new Error(messages.warnings.join('\n\n')));
  150. }
  151. const resolveArgs = {
  152. stats,
  153. previousFileSizes,
  154. warnings: messages.warnings,
  155. };
  156. if (writeStatsJson) {
  157. return bfj
  158. .write(paths.appBuild + '/bundle-stats.json', stats.toJson())
  159. .then(() => resolve(resolveArgs))
  160. .catch(error => reject(new Error(error)));
  161. }
  162. return resolve(resolveArgs);
  163. });
  164. });
  165. }
  166. function copyPublicFolder() {
  167. fs.copySync(paths.appPublic, paths.appBuild, {
  168. dereference: true,
  169. filter: file => file !== paths.appHtml,
  170. });
  171. }