UNPKG

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