You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

199 lines
6.4 KiB

  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.publicUrl;
  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(chalk.yellow(
  99. 'Compiled with the following type errors (you may want to check these before deploying your app):\n'
  100. ));
  101. printBuildError(err);
  102. } else {
  103. console.log(chalk.red('Failed to compile.\n'));
  104. printBuildError(err);
  105. process.exit(1);
  106. }
  107. }
  108. )
  109. .catch(err => {
  110. if (err && err.message) {
  111. console.log(err.message);
  112. }
  113. process.exit(1);
  114. });
  115. // Create the production build and print the deployment instructions.
  116. function build(previousFileSizes) {
  117. // We used to support resolving modules according to `NODE_PATH`.
  118. // This now has been deprecated in favor of jsconfig/tsconfig.json
  119. // This lets you use absolute paths in imports inside large monorepos:
  120. if (process.env.NODE_PATH) {
  121. console.log(
  122. chalk.yellow(
  123. '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.'
  124. )
  125. );
  126. console.log();
  127. }
  128. console.log('Creating an optimized production build...');
  129. const compiler = webpack(config);
  130. return new Promise((resolve, reject) => {
  131. compiler.run((err, stats) => {
  132. let messages;
  133. if (err) {
  134. if (!err.message) {
  135. return reject(err);
  136. }
  137. messages = formatWebpackMessages({
  138. errors: [err.message],
  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. return resolve({
  169. stats,
  170. previousFileSizes,
  171. warnings: messages.warnings,
  172. });
  173. });
  174. });
  175. }
  176. function copyPublicFolder() {
  177. fs.copySync(paths.appPublic, paths.appBuild, {
  178. dereference: true,
  179. filter: file => file !== paths.appHtml,
  180. });
  181. }