build.js 6.01 KB
Newer Older
1
// @remove-on-eject-begin
Christopher Chedeau's avatar
Christopher Chedeau committed
2
3
4
/**
 * Copyright (c) 2015-present, Facebook, Inc.
 *
Sophie Alpert's avatar
Sophie Alpert committed
5
6
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
Christopher Chedeau's avatar
Christopher Chedeau committed
7
 */
8
// @remove-on-eject-end
9
'use strict';
Christopher Chedeau's avatar
Christopher Chedeau committed
10

11
// Do this as the first thing so that any code reading it knows the right env.
12
process.env.BABEL_ENV = 'production';
13
14
process.env.NODE_ENV = 'production';

15
16
17
18
19
20
21
// Makes the script crash on unhandled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will
// terminate the Node.js process with a non-zero exit code.
process.on('unhandledRejection', err => {
  throw err;
});

22
23
// Ensure environment variables are read.
require('../config/env');
24
25
26
27
28
29
30
// @remove-on-eject-begin
// Do the preflight check (only happens before eject).
const verifyPackageTree = require('./utils/verifyPackageTree');
if (process.env.SKIP_PREFLIGHT_CHECK !== 'true') {
  verifyPackageTree();
}
// @remove-on-eject-end
31

32
const path = require('path');
33
34
35
const chalk = require('chalk');
const fs = require('fs-extra');
const webpack = require('webpack');
36
const bfj = require('bfj');
37
38
39
const config = require('../config/webpack.config.prod');
const paths = require('../config/paths');
const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
40
41
const formatWebpackMessages = require('react-dev-utils/formatWebpackMessages');
const printHostingInstructions = require('react-dev-utils/printHostingInstructions');
42
const FileSizeReporter = require('react-dev-utils/FileSizeReporter');
43
const printBuildError = require('react-dev-utils/printBuildError');
44

45
46
const measureFileSizesBeforeBuild =
  FileSizeReporter.measureFileSizesBeforeBuild;
47
const printFileSizesAfterBuild = FileSizeReporter.printFileSizesAfterBuild;
48
const useYarn = fs.existsSync(paths.yarnLockFile);
Ville Immonen's avatar
Ville Immonen committed
49

50
51
52
53
// These sizes are pretty large. We'll warn for bundles exceeding them.
const WARN_AFTER_BUNDLE_GZIP_SIZE = 512 * 1024;
const WARN_AFTER_CHUNK_GZIP_SIZE = 1024 * 1024;

54
55
56
57
// Warn and crash if required files are missing
if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
  process.exit(1);
}
58

59
60
61
62
// Process CLI arguments
const argv = process.argv.slice(2);
const writeStatsJson = argv.indexOf('--stats') !== -1;

63
64
65
66
67
68
69
70
71
// We require that you explictly set browsers and do not fall back to
// browserslist defaults.
const { checkBrowsers } = require('react-dev-utils/browsersHelper');
checkBrowsers(paths.appPath)
  .then(() => {
    // First, read the current file sizes in build directory.
    // This lets us display how much they changed later.
    return measureFileSizesBeforeBuild(paths.appBuild);
  })
72
73
74
75
76
77
78
79
80
81
  .then(previousFileSizes => {
    // Remove all content but keep the directory so that
    // if you're in it, you don't end up in Trash
    fs.emptyDirSync(paths.appBuild);
    // Merge with the public folder
    copyPublicFolder();
    // Start the webpack build
    return build(previousFileSizes);
  })
  .then(
82
83
84
85
86
87
    ({ stats, previousFileSizes, warnings }) => {
      if (warnings.length) {
        console.log(chalk.yellow('Compiled with warnings.\n'));
        console.log(warnings.join('\n\n'));
        console.log(
          '\nSearch for the ' +
Dan Abramov's avatar
Dan Abramov committed
88
            chalk.underline(chalk.yellow('keywords')) +
89
90
91
92
93
94
95
96
97
98
            ' to learn more about each warning.'
        );
        console.log(
          'To ignore, add ' +
            chalk.cyan('// eslint-disable-next-line') +
            ' to the line before.\n'
        );
      } else {
        console.log(chalk.green('Compiled successfully.\n'));
      }
99

100
      console.log('File sizes after gzip:\n');
101
102
103
104
105
106
107
      printFileSizesAfterBuild(
        stats,
        previousFileSizes,
        paths.appBuild,
        WARN_AFTER_BUNDLE_GZIP_SIZE,
        WARN_AFTER_CHUNK_GZIP_SIZE
      );
108
      console.log();
109

110
111
112
113
114
115
116
117
118
      const appPackage = require(paths.appPackageJson);
      const publicUrl = paths.publicUrl;
      const publicPath = config.output.publicPath;
      const buildFolder = path.relative(process.cwd(), paths.appBuild);
      printHostingInstructions(
        appPackage,
        publicUrl,
        publicPath,
        buildFolder,
119
        useYarn
120
      );
121
122
    },
    err => {
123
      console.log(chalk.red('Failed to compile.\n'));
124
      printBuildError(err);
125
126
      process.exit(1);
    }
127
128
129
130
131
132
133
  )
  .catch(err => {
    if (err && err.message) {
      console.log(err.message);
    }
    process.exit(1);
  });
134

135
136
137
// Create the production build and print the deployment instructions.
function build(previousFileSizes) {
  console.log('Creating an optimized production build...');
Elijah Manor's avatar
Elijah Manor committed
138

139
140
141
142
143
  let compiler = webpack(config);
  return new Promise((resolve, reject) => {
    compiler.run((err, stats) => {
      if (err) {
        return reject(err);
Ville Immonen's avatar
Ville Immonen committed
144
      }
145
146
      const messages = formatWebpackMessages(stats.toJson({}, true));
      if (messages.errors.length) {
147
148
149
150
151
        // Only keep the first error. Others are often indicative
        // of the same problem, but confuse the reader with noise.
        if (messages.errors.length > 1) {
          messages.errors.length = 1;
        }
152
153
        return reject(new Error(messages.errors.join('\n\n')));
      }
Joe Haddad's avatar
Joe Haddad committed
154
155
156
157
158
159
      if (
        process.env.CI &&
        (typeof process.env.CI !== 'string' ||
          process.env.CI.toLowerCase() !== 'false') &&
        messages.warnings.length
      ) {
160
        console.log(
161
          chalk.yellow(
162
163
            '\nTreating warnings as errors because process.env.CI = true.\n' +
              'Most CI servers set it automatically.\n'
164
          )
165
        );
166
        return reject(new Error(messages.warnings.join('\n\n')));
Dan Abramov's avatar
Dan Abramov committed
167
      }
168
169

      const resolveArgs = {
170
171
172
        stats,
        previousFileSizes,
        warnings: messages.warnings,
173
174
175
176
177
178
179
180
181
      };
      if (writeStatsJson) {
        return bfj
          .write(paths.appBuild + '/bundle-stats.json', stats.toJson())
          .then(() => resolve(resolveArgs))
          .catch(error => reject(new Error(error)));
      }

      return resolve(resolveArgs);
182
    });
Elijah Manor's avatar
Elijah Manor committed
183
184
  });
}
185
186
187
188

function copyPublicFolder() {
  fs.copySync(paths.appPublic, paths.appBuild, {
    dereference: true,
189
    filter: file => file !== paths.appHtml,
190
191
  });
}