UNPKG

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