build.js 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. // Do this as the first thing so that any code reading it knows the right env.
  2. process.env.BABEL_ENV = 'production';
  3. process.env.NODE_ENV = 'production';
  4. // Makes the script crash on unhandled rejections instead of silently
  5. // ignoring them. In the future, promise rejections that are not handled will
  6. // terminate the Node.js process with a non-zero exit code.
  7. process.on('unhandledRejection', err => {
  8. throw err;
  9. });
  10. // Ensure environment variables are read.
  11. require('../config/env');
  12. const path = require('path');
  13. const chalk = require('react-dev-utils/chalk');
  14. const fs = require('fs-extra');
  15. const bfj = require('bfj');
  16. const webpack = require('webpack');
  17. const configFactory = require('../config/webpack.config');
  18. const paths = require('../config/paths');
  19. const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
  20. const formatWebpackMessages = require('react-dev-utils/formatWebpackMessages');
  21. const printHostingInstructions = require('react-dev-utils/printHostingInstructions');
  22. const FileSizeReporter = require('react-dev-utils/FileSizeReporter');
  23. const printBuildError = require('react-dev-utils/printBuildError');
  24. const measureFileSizesBeforeBuild =
  25. FileSizeReporter.measureFileSizesBeforeBuild;
  26. const printFileSizesAfterBuild = FileSizeReporter.printFileSizesAfterBuild;
  27. const useYarn = fs.existsSync(paths.yarnLockFile);
  28. // These sizes are pretty large. We'll warn for bundles exceeding them.
  29. const WARN_AFTER_BUNDLE_GZIP_SIZE = 512 * 1024;
  30. const WARN_AFTER_CHUNK_GZIP_SIZE = 1024 * 1024;
  31. const isInteractive = process.stdout.isTTY;
  32. // Warn and crash if required files are missing
  33. if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
  34. process.exit(1);
  35. }
  36. const argv = process.argv.slice(2);
  37. const writeStatsJson = argv.indexOf('--stats') !== -1;
  38. // Generate configuration
  39. const config = configFactory('production');
  40. // We require that you explicitly 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.publicUrlOrPath;
  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. const tscCompileOnError = process.env.TSC_COMPILE_ON_ERROR === 'true';
  99. if (tscCompileOnError) {
  100. console.log(
  101. chalk.yellow(
  102. 'Compiled with the following type errors (you may want to check these before deploying your app):\n'
  103. )
  104. );
  105. printBuildError(err);
  106. } else {
  107. console.log(chalk.red('Failed to compile.\n'));
  108. printBuildError(err);
  109. process.exit(1);
  110. }
  111. }
  112. )
  113. .catch(err => {
  114. if (err && err.message) {
  115. console.log(err.message);
  116. }
  117. process.exit(1);
  118. });
  119. // Create the production build and print the deployment instructions.
  120. function build(previousFileSizes) {
  121. console.log('Creating an optimized production build...');
  122. const compiler = webpack(config);
  123. return new Promise((resolve, reject) => {
  124. compiler.run((err, stats) => {
  125. let messages;
  126. if (err) {
  127. if (!err.message) {
  128. return reject(err);
  129. }
  130. let errMessage = err.message;
  131. // Add additional information for postcss errors
  132. if (Object.prototype.hasOwnProperty.call(err, 'postcssNode')) {
  133. errMessage +=
  134. '\nCompileError: Begins at CSS selector ' +
  135. err['postcssNode'].selector;
  136. }
  137. messages = formatWebpackMessages({
  138. errors: [errMessage],
  139. warnings: [],
  140. });
  141. } else {
  142. messages = formatWebpackMessages(
  143. stats.toJson({ all: false, warnings: true, errors: true })
  144. );
  145. }
  146. if (messages.errors.length) {
  147. // Only keep the first error. Others are often indicative
  148. // of the same problem, but confuse the reader with noise.
  149. if (messages.errors.length > 1) {
  150. messages.errors.length = 1;
  151. }
  152. return reject(new Error(messages.errors.join('\n\n')));
  153. }
  154. if (
  155. process.env.CI &&
  156. (typeof process.env.CI !== 'string' ||
  157. process.env.CI.toLowerCase() !== 'false') &&
  158. messages.warnings.length
  159. ) {
  160. console.log(
  161. chalk.yellow(
  162. '\nTreating warnings as errors because process.env.CI = true.\n' +
  163. 'Most CI servers set it automatically.\n'
  164. )
  165. );
  166. return reject(new Error(messages.warnings.join('\n\n')));
  167. }
  168. const resolveArgs = {
  169. stats,
  170. previousFileSizes,
  171. warnings: messages.warnings,
  172. };
  173. if (writeStatsJson) {
  174. return bfj
  175. .write(paths.appBuild + '/bundle-stats.json', stats.toJson())
  176. .then(() => resolve(resolveArgs))
  177. .catch(error => reject(new Error(error)));
  178. }
  179. return resolve(resolveArgs);
  180. });
  181. });
  182. }
  183. function copyPublicFolder() {
  184. fs.copySync(paths.appPublic, paths.appBuild, {
  185. dereference: true,
  186. filter: file => file !== paths.appHtml,
  187. });
  188. }