build.js 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. // Do this as the first thing so that any code reading it knows the right env.
  2. process.env.NODE_ENV = 'production';
  3. // Load environment variables from .env file. Suppress warnings using silent
  4. // if this file is missing. dotenv will never modify any environment variables
  5. // that have already been set.
  6. // https://github.com/motdotla/dotenv
  7. require('dotenv').config({silent: true});
  8. var chalk = require('chalk');
  9. var fs = require('fs-extra');
  10. var path = require('path');
  11. var pathExists = require('path-exists');
  12. var filesize = require('filesize');
  13. var gzipSize = require('gzip-size').sync;
  14. var webpack = require('webpack');
  15. var config = require('../config/webpack.config.prod');
  16. var paths = require('../config/paths');
  17. var checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
  18. var recursive = require('recursive-readdir');
  19. var stripAnsi = require('strip-ansi');
  20. var useYarn = pathExists.sync(paths.yarnLockFile);
  21. // Warn and crash if required files are missing
  22. if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
  23. process.exit(1);
  24. }
  25. // Input: /User/dan/app/build/static/js/main.82be8.js
  26. // Output: /static/js/main.js
  27. function removeFileNameHash(fileName) {
  28. return fileName
  29. .replace(paths.appBuild, '')
  30. .replace(/\/?(.*)(\.\w+)(\.js|\.css)/, (match, p1, p2, p3) => p1 + p3);
  31. }
  32. // Input: 1024, 2048
  33. // Output: "(+1 KB)"
  34. function getDifferenceLabel(currentSize, previousSize) {
  35. var FIFTY_KILOBYTES = 1024 * 50;
  36. var difference = currentSize - previousSize;
  37. var fileSize = !Number.isNaN(difference) ? filesize(difference) : 0;
  38. if (difference >= FIFTY_KILOBYTES) {
  39. return chalk.red('+' + fileSize);
  40. } else if (difference < FIFTY_KILOBYTES && difference > 0) {
  41. return chalk.yellow('+' + fileSize);
  42. } else if (difference < 0) {
  43. return chalk.green(fileSize);
  44. } else {
  45. return '';
  46. }
  47. }
  48. // First, read the current file sizes in build directory.
  49. // This lets us display how much they changed later.
  50. recursive(paths.appBuild, (err, fileNames) => {
  51. var previousSizeMap = (fileNames || [])
  52. .filter(fileName => /\.(js|css)$/.test(fileName))
  53. .reduce((memo, fileName) => {
  54. var contents = fs.readFileSync(fileName);
  55. var key = removeFileNameHash(fileName);
  56. memo[key] = gzipSize(contents);
  57. return memo;
  58. }, {});
  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. // Start the webpack build
  63. build(previousSizeMap);
  64. // Merge with the public folder
  65. copyPublicFolder();
  66. });
  67. // Print a detailed summary of build files.
  68. function printFileSizes(stats, previousSizeMap) {
  69. var assets = stats.toJson().assets
  70. .filter(asset => /\.(js|css)$/.test(asset.name))
  71. .map(asset => {
  72. var fileContents = fs.readFileSync(paths.appBuild + '/' + asset.name);
  73. var size = gzipSize(fileContents);
  74. var previousSize = previousSizeMap[removeFileNameHash(asset.name)];
  75. var difference = getDifferenceLabel(size, previousSize);
  76. return {
  77. folder: path.join('build_webpack', path.dirname(asset.name)),
  78. name: path.basename(asset.name),
  79. size: size,
  80. sizeLabel: filesize(size) + (difference ? ' (' + difference + ')' : '')
  81. };
  82. });
  83. assets.sort((a, b) => b.size - a.size);
  84. var longestSizeLabelLength = Math.max.apply(null,
  85. assets.map(a => stripAnsi(a.sizeLabel).length)
  86. );
  87. assets.forEach(asset => {
  88. var sizeLabel = asset.sizeLabel;
  89. var sizeLength = stripAnsi(sizeLabel).length;
  90. if (sizeLength < longestSizeLabelLength) {
  91. var rightPadding = ' '.repeat(longestSizeLabelLength - sizeLength);
  92. sizeLabel += rightPadding;
  93. }
  94. console.log(
  95. ' ' + sizeLabel +
  96. ' ' + chalk.dim(asset.folder + path.sep) + chalk.cyan(asset.name)
  97. );
  98. });
  99. }
  100. // Print out errors
  101. function printErrors(summary, errors) {
  102. console.log(chalk.red(summary));
  103. console.log();
  104. errors.forEach(err => {
  105. console.log(err.message || err);
  106. console.log();
  107. });
  108. }
  109. // Create the production build and print the deployment instructions.
  110. function build(previousSizeMap) {
  111. console.log('Creating an optimized production build...');
  112. webpack(config).run((err, stats) => {
  113. if (err) {
  114. printErrors('Failed to compile.', [err]);
  115. process.exit(1);
  116. }
  117. if (stats.compilation.errors.length) {
  118. printErrors('Failed to compile.', stats.compilation.errors);
  119. process.exit(1);
  120. }
  121. if (process.env.CI && stats.compilation.warnings.length) {
  122. printErrors('Failed to compile.', stats.compilation.warnings);
  123. process.exit(1);
  124. }
  125. console.log(chalk.green('Compiled successfully.'));
  126. console.log();
  127. console.log('File sizes after gzip:');
  128. console.log();
  129. printFileSizes(stats, previousSizeMap);
  130. console.log();
  131. var openCommand = process.platform === 'win32' ? 'start' : 'open';
  132. var appPackage = require(paths.appPackageJson);
  133. var homepagePath = appPackage.homepage;
  134. var publicPath = config.output.publicPath;
  135. if (homepagePath && homepagePath.indexOf('.github.io/') !== -1) {
  136. // "homepage": "http://user.github.io/project"
  137. console.log('The project was built assuming it is hosted at ' + chalk.green(publicPath) + '.');
  138. console.log('You can control this with the ' + chalk.green('homepage') + ' field in your ' + chalk.cyan('package.json') + '.');
  139. console.log();
  140. console.log('The ' + chalk.cyan('build_webpack') + ' folder is ready to be deployed.');
  141. console.log('To publish it at ' + chalk.green(homepagePath) + ', run:');
  142. // If script deploy has been added to package.json, skip the instructions
  143. if (typeof appPackage.scripts.deploy === 'undefined') {
  144. console.log();
  145. if (useYarn) {
  146. console.log(' ' + chalk.cyan('yarn') + ' add --dev gh-pages');
  147. } else {
  148. console.log(' ' + chalk.cyan('npm') + ' install --save-dev gh-pages');
  149. }
  150. console.log();
  151. console.log('Add the following script in your ' + chalk.cyan('package.json') + '.');
  152. console.log();
  153. console.log(' ' + chalk.dim('// ...'));
  154. console.log(' ' + chalk.yellow('"scripts"') + ': {');
  155. console.log(' ' + chalk.dim('// ...'));
  156. console.log(' ' + chalk.yellow('"deploy"') + ': ' + chalk.yellow('"npm run build&&gh-pages -d build"'));
  157. console.log(' }');
  158. console.log();
  159. console.log('Then run:');
  160. }
  161. console.log();
  162. console.log(' ' + chalk.cyan(useYarn ? 'yarn' : 'npm') + ' run deploy');
  163. console.log();
  164. } else if (publicPath !== '/') {
  165. // "homepage": "http://mywebsite.com/project"
  166. console.log('The project was built assuming it is hosted at ' + chalk.green(publicPath) + '.');
  167. console.log('You can control this with the ' + chalk.green('homepage') + ' field in your ' + chalk.cyan('package.json') + '.');
  168. console.log();
  169. console.log('The ' + chalk.cyan('build_webpack') + ' folder is ready to be deployed.');
  170. console.log();
  171. } else {
  172. // no homepage or "homepage": "http://mywebsite.com"
  173. console.log('The project was built assuming it is hosted at the server root.');
  174. if (homepagePath) {
  175. // "homepage": "http://mywebsite.com"
  176. console.log('You can control this with the ' + chalk.green('homepage') + ' field in your ' + chalk.cyan('package.json') + '.');
  177. console.log();
  178. } else {
  179. // no homepage
  180. console.log('To override this, specify the ' + chalk.green('homepage') + ' in your ' + chalk.cyan('package.json') + '.');
  181. console.log('For example, add this to build it for GitHub Pages:')
  182. console.log();
  183. console.log(' ' + chalk.green('"homepage"') + chalk.cyan(': ') + chalk.green('"http://myname.github.io/myapp"') + chalk.cyan(','));
  184. console.log();
  185. }
  186. console.log('The ' + chalk.cyan('build_webpack') + ' folder is ready to be deployed.');
  187. console.log('You may also serve it locally with a static server:')
  188. console.log();
  189. if (useYarn) {
  190. console.log(' ' + chalk.cyan('yarn') + ' global add pushstate-server');
  191. } else {
  192. console.log(' ' + chalk.cyan('npm') + ' install -g pushstate-server');
  193. }
  194. console.log(' ' + chalk.cyan('pushstate-server') + ' build');
  195. console.log(' ' + chalk.cyan(openCommand) + ' http://localhost:9000');
  196. console.log();
  197. }
  198. });
  199. }
  200. function copyPublicFolder() {
  201. fs.copySync(paths.appPublic, paths.appBuild, {
  202. dereference: true,
  203. filter: file => file !== paths.appHtml
  204. });
  205. }