build.js 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  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('react-dev-utils/chalk');
  15. const fs = require('fs-extra');
  16. const webpack = require('webpack');
  17. const bfj = require('bfj');
  18. const configFactory = require('../config/webpack.config');
  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. // Generate configuration
  41. const config = configFactory('production');
  42. // We require that you explicitly set browsers and do not fall back to
  43. // browserslist defaults.
  44. const { checkBrowsers } = require('react-dev-utils/browsersHelper');
  45. checkBrowsers(paths.appPath, isInteractive)
  46. .then(() => {
  47. // First, read the current file sizes in build directory.
  48. // This lets us display how much they changed later.
  49. return measureFileSizesBeforeBuild(paths.appBuild);
  50. })
  51. .then(previousFileSizes => {
  52. // Remove all content but keep the directory so that
  53. // if you're in it, you don't end up in Trash
  54. fs.emptyDirSync(paths.appBuild);
  55. // Merge with the public folder
  56. copyPublicFolder();
  57. // Start the webpack build
  58. return build(previousFileSizes);
  59. })
  60. .then(
  61. ({ stats, previousFileSizes, warnings }) => {
  62. if (warnings.length) {
  63. console.log(chalk.yellow('Compiled with warnings.\n'));
  64. console.log(warnings.join('\n\n'));
  65. console.log(
  66. '\nSearch for the ' +
  67. chalk.underline(chalk.yellow('keywords')) +
  68. ' to learn more about each warning.'
  69. );
  70. console.log(
  71. 'To ignore, add ' +
  72. chalk.cyan('// eslint-disable-next-line') +
  73. ' to the line before.\n'
  74. );
  75. } else {
  76. console.log(chalk.green('Compiled successfully.\n'));
  77. }
  78. console.log('File sizes after gzip:\n');
  79. printFileSizesAfterBuild(
  80. stats,
  81. previousFileSizes,
  82. paths.appBuild,
  83. WARN_AFTER_BUNDLE_GZIP_SIZE,
  84. WARN_AFTER_CHUNK_GZIP_SIZE
  85. );
  86. console.log();
  87. const appPackage = require(paths.appPackageJson);
  88. const publicUrl = paths.publicUrl;
  89. const publicPath = config.output.publicPath;
  90. const buildFolder = path.relative(process.cwd(), paths.appBuild);
  91. printHostingInstructions(
  92. appPackage,
  93. publicUrl,
  94. publicPath,
  95. buildFolder,
  96. useYarn
  97. );
  98. },
  99. err => {
  100. console.log(chalk.red('Failed to compile.\n'));
  101. printBuildError(err);
  102. process.exit(1);
  103. }
  104. )
  105. .catch(err => {
  106. if (err && err.message) {
  107. console.log(err.message);
  108. }
  109. process.exit(1);
  110. });
  111. // Create the production build and print the deployment instructions.
  112. function build(previousFileSizes) {
  113. console.log('Creating an optimized production build...');
  114. let compiler = webpack(config);
  115. return new Promise((resolve, reject) => {
  116. compiler.run((err, stats) => {
  117. let messages;
  118. if (err) {
  119. if (!err.message) {
  120. return reject(err);
  121. }
  122. messages = formatWebpackMessages({
  123. errors: [err.message],
  124. warnings: [],
  125. });
  126. } else {
  127. messages = formatWebpackMessages(
  128. stats.toJson({ all: false, warnings: true, errors: true })
  129. );
  130. }
  131. if (messages.errors.length) {
  132. // Only keep the first error. Others are often indicative
  133. // of the same problem, but confuse the reader with noise.
  134. if (messages.errors.length > 1) {
  135. messages.errors.length = 1;
  136. }
  137. return reject(new Error(messages.errors.join('\n\n')));
  138. }
  139. if (
  140. process.env.CI &&
  141. (typeof process.env.CI !== 'string' ||
  142. process.env.CI.toLowerCase() !== 'false') &&
  143. messages.warnings.length
  144. ) {
  145. console.log(
  146. chalk.yellow(
  147. '\nTreating warnings as errors because process.env.CI = true.\n' +
  148. 'Most CI servers set it automatically.\n'
  149. )
  150. );
  151. return reject(new Error(messages.warnings.join('\n\n')));
  152. }
  153. const resolveArgs = {
  154. stats,
  155. previousFileSizes,
  156. warnings: messages.warnings,
  157. };
  158. if (writeStatsJson) {
  159. return bfj
  160. .write(paths.appBuild + '/bundle-stats.json', stats.toJson())
  161. .then(() => resolve(resolveArgs))
  162. .catch(error => reject(new Error(error)));
  163. }
  164. return resolve(resolveArgs);
  165. });
  166. });
  167. }
  168. function copyPublicFolder() {
  169. fs.copySync(paths.appPublic, paths.appBuild, {
  170. dereference: true,
  171. filter: file => file !== paths.appHtml,
  172. });
  173. }