build.js 7.7 KB

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