build.js 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  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 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. // Generate configuration
  37. const config = configFactory('production');
  38. // We require that you explicitly set browsers and do not fall back to
  39. // browserslist defaults.
  40. const { checkBrowsers } = require('react-dev-utils/browsersHelper');
  41. checkBrowsers(paths.appPath, isInteractive)
  42. .then(() => {
  43. // First, read the current file sizes in build directory.
  44. // This lets us display how much they changed later.
  45. return measureFileSizesBeforeBuild(paths.appBuild);
  46. })
  47. .then(previousFileSizes => {
  48. // Remove all content but keep the directory so that
  49. // if you're in it, you don't end up in Trash
  50. fs.emptyDirSync(paths.appBuild);
  51. // Merge with the public folder
  52. copyPublicFolder();
  53. // Start the webpack build
  54. return build(previousFileSizes);
  55. })
  56. .then(
  57. ({ stats, previousFileSizes, warnings }) => {
  58. if (warnings.length) {
  59. console.log(chalk.yellow('Compiled with warnings.\n'));
  60. console.log(warnings.join('\n\n'));
  61. console.log(
  62. '\nSearch for the ' +
  63. chalk.underline(chalk.yellow('keywords')) +
  64. ' to learn more about each warning.'
  65. );
  66. console.log(
  67. 'To ignore, add ' +
  68. chalk.cyan('// eslint-disable-next-line') +
  69. ' to the line before.\n'
  70. );
  71. } else {
  72. console.log(chalk.green('Compiled successfully.\n'));
  73. }
  74. console.log('File sizes after gzip:\n');
  75. printFileSizesAfterBuild(
  76. stats,
  77. previousFileSizes,
  78. paths.appBuild,
  79. WARN_AFTER_BUNDLE_GZIP_SIZE,
  80. WARN_AFTER_CHUNK_GZIP_SIZE
  81. );
  82. console.log();
  83. const appPackage = require(paths.appPackageJson);
  84. const publicUrl = paths.publicUrlOrPath;
  85. const publicPath = config.output.publicPath;
  86. const buildFolder = path.relative(process.cwd(), paths.appBuild);
  87. printHostingInstructions(
  88. appPackage,
  89. publicUrl,
  90. publicPath,
  91. buildFolder,
  92. useYarn
  93. );
  94. },
  95. err => {
  96. const tscCompileOnError = process.env.TSC_COMPILE_ON_ERROR === 'true';
  97. if (tscCompileOnError) {
  98. console.log(
  99. chalk.yellow(
  100. 'Compiled with the following type errors (you may want to check these before deploying your app):\n'
  101. )
  102. );
  103. printBuildError(err);
  104. } else {
  105. console.log(chalk.red('Failed to compile.\n'));
  106. printBuildError(err);
  107. process.exit(1);
  108. }
  109. }
  110. )
  111. .catch(err => {
  112. if (err && err.message) {
  113. console.log(err.message);
  114. }
  115. process.exit(1);
  116. });
  117. // Create the production build and print the deployment instructions.
  118. function build(previousFileSizes) {
  119. // We used to support resolving modules according to `NODE_PATH`.
  120. // This now has been deprecated in favor of jsconfig/tsconfig.json
  121. // This lets you use absolute paths in imports inside large monorepos:
  122. if (process.env.NODE_PATH) {
  123. console.log(
  124. chalk.yellow(
  125. 'Setting NODE_PATH to resolve modules absolutely has been deprecated in favor of setting baseUrl in jsconfig.json (or tsconfig.json if you are using TypeScript) and will be removed in a future major release of create-react-app.'
  126. )
  127. );
  128. console.log();
  129. }
  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. console.log(
  170. chalk.yellow(
  171. '\nTreating warnings as errors because process.env.CI = true.\n' +
  172. 'Most CI servers set it automatically.\n'
  173. )
  174. );
  175. return reject(new Error(messages.warnings.join('\n\n')));
  176. }
  177. return resolve({
  178. stats,
  179. previousFileSizes,
  180. warnings: messages.warnings,
  181. });
  182. });
  183. });
  184. }
  185. function copyPublicFolder() {
  186. fs.copySync(paths.appPublic, paths.appBuild, {
  187. dereference: true,
  188. filter: file => file !== paths.appHtml,
  189. });
  190. }