build.js 7.0 KB

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