build.js 4.54 KB
Newer Older
1
// @remove-on-eject-begin
Christopher Chedeau's avatar
Christopher Chedeau committed
2
3
4
5
6
7
8
9
/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */
10
// @remove-on-eject-end
11
'use strict';
Christopher Chedeau's avatar
Christopher Chedeau committed
12

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

17
18
19
20
21
22
23
// 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;
});

24
25
// Ensure environment variables are read.
require('../config/env');
26

27
const path = require('path');
28
29
30
31
32
33
const chalk = require('chalk');
const fs = require('fs-extra');
const webpack = require('webpack');
const config = require('../config/webpack.config.prod');
const paths = require('../config/paths');
const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
34
35
const formatWebpackMessages = require('react-dev-utils/formatWebpackMessages');
const printHostingInstructions = require('react-dev-utils/printHostingInstructions');
36
37
38
39
40
const FileSizeReporter = require('react-dev-utils/FileSizeReporter');

const measureFileSizesBeforeBuild = FileSizeReporter.measureFileSizesBeforeBuild;
const printFileSizesAfterBuild = FileSizeReporter.printFileSizesAfterBuild;
const useYarn = fs.existsSync(paths.yarnLockFile);
Ville Immonen's avatar
Ville Immonen committed
41

42
43
44
45
// Warn and crash if required files are missing
if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
  process.exit(1);
}
46

Dan Abramov's avatar
Dan Abramov committed
47
48
// First, read the current file sizes in build directory.
// This lets us display how much they changed later.
49
50
51
52
53
54
55
56
57
58
59
measureFileSizesBeforeBuild(paths.appBuild)
  .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(
60
61
62
63
64
65
    ({ 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
66
            chalk.underline(chalk.yellow('keywords')) +
67
68
69
70
71
72
73
74
75
76
            ' 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'));
      }
77

78
      console.log('File sizes after gzip:\n');
79
      printFileSizesAfterBuild(stats, previousFileSizes, paths.appBuild);
80
      console.log();
81

82
83
84
85
86
87
88
89
90
91
      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,
        useYarn
92
      );
93
94
    },
    err => {
95
96
      console.log(chalk.red('Failed to compile.\n'));
      console.log((err.message || err) + '\n');
97
98
      process.exit(1);
    }
99
  );
100

101
102
103
// 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
104

105
106
107
108
109
  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
110
      }
111
112
113
114
      const messages = formatWebpackMessages(stats.toJson({}, true));
      if (messages.errors.length) {
        return reject(new Error(messages.errors.join('\n\n')));
      }
115
      if (process.env.CI && process.env.CI.toLowerCase() !== 'false' && messages.warnings.length) {
116
        console.log(
117
          chalk.yellow(
118
119
            '\nTreating warnings as errors because process.env.CI = true.\n' +
              'Most CI servers set it automatically.\n'
120
          )
121
        );
122
        return reject(new Error(messages.warnings.join('\n\n')));
Dan Abramov's avatar
Dan Abramov committed
123
      }
124
125
126
127
128
      return resolve({
        stats,
        previousFileSizes,
        warnings: messages.warnings,
      });
129
    });
Elijah Manor's avatar
Elijah Manor committed
130
131
  });
}
132
133
134
135

function copyPublicFolder() {
  fs.copySync(paths.appPublic, paths.appBuild, {
    dereference: true,
136
    filter: file => file !== paths.appHtml,
137
138
  });
}