build.js 7 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
15
process.env.NODE_ENV = 'production';

Brian Ng's avatar
Brian Ng committed
16
// Load environment variables from .env file. Suppress warnings using silent
17
18
19
// if this file is missing. dotenv will never modify any environment variables
// that have already been set.
// https://github.com/motdotla/dotenv
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
require('dotenv').config({ silent: true });

const chalk = require('chalk');
const fs = require('fs-extra');
const path = require('path');
const url = require('url');
const webpack = require('webpack');
const config = require('../config/webpack.config.prod');
const paths = require('../config/paths');
const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
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
35

36
37
38
39
// Warn and crash if required files are missing
if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
  process.exit(1);
}
40

Dan Abramov's avatar
Dan Abramov committed
41
42
// First, read the current file sizes in build directory.
// This lets us display how much they changed later.
43
measureFileSizesBeforeBuild(paths.appBuild).then(previousFileSizes => {
Elijah Manor's avatar
Elijah Manor committed
44
45
  // Remove all content but keep the directory so that
  // if you're in it, you don't end up in Trash
46
  fs.emptyDirSync(paths.appBuild);
Elijah Manor's avatar
Elijah Manor committed
47

Dan Abramov's avatar
Dan Abramov committed
48
  // Start the webpack build
49
  build(previousFileSizes);
50
51
52

  // Merge with the public folder
  copyPublicFolder();
Elijah Manor's avatar
Elijah Manor committed
53
});
54

55
56
57
58
59
60
61
62
63
64
// Print out errors
function printErrors(summary, errors) {
  console.log(chalk.red(summary));
  console.log();
  errors.forEach(err => {
    console.log(err.message || err);
    console.log();
  });
}

65
// Create the production build and print the deployment instructions.
66
function build(previousFileSizes) {
Elijah Manor's avatar
Elijah Manor committed
67
  console.log('Creating an optimized production build...');
68

69
  let compiler;
70
71
72
73
74
75
76
77
  try {
    compiler = webpack(config);
  } catch (err) {
    printErrors('Failed to compile.', [err]);
    process.exit(1);
  }

  compiler.run((err, stats) => {
Elijah Manor's avatar
Elijah Manor committed
78
    if (err) {
79
80
81
82
83
84
      printErrors('Failed to compile.', [err]);
      process.exit(1);
    }

    if (stats.compilation.errors.length) {
      printErrors('Failed to compile.', stats.compilation.errors);
Elijah Manor's avatar
Elijah Manor committed
85
      process.exit(1);
86
    }
87

88
    if (process.env.CI && stats.compilation.warnings.length) {
89
90
91
92
93
94
      printErrors(
        'Failed to compile. When process.env.CI = true, warnings are treated as failures. Most CI servers set this automatically.',
        stats.compilation.warnings
      );
      process.exit(1);
    }
95

Elijah Manor's avatar
Elijah Manor committed
96
    console.log(chalk.green('Compiled successfully.'));
97
    console.log();
Elijah Manor's avatar
Elijah Manor committed
98
99

    console.log('File sizes after gzip:');
100
    console.log();
101
    printFileSizesAfterBuild(stats, previousFileSizes);
102
    console.log();
Elijah Manor's avatar
Elijah Manor committed
103

104
105
106
107
    const appPackage = require(paths.appPackageJson);
    const publicUrl = paths.publicUrl;
    const publicPath = config.output.publicPath;
    const publicPathname = url.parse(publicPath).pathname;
108
    if (publicUrl && publicUrl.indexOf('.github.io/') !== -1) {
Dan Abramov's avatar
Dan Abramov committed
109
      // "homepage": "http://user.github.io/project"
110
111
112
113
114
115
      console.log(
        `The project was built assuming it is hosted at ${chalk.green(publicPathname)}.`
      );
      console.log(
        `You can control this with the ${chalk.green('homepage')} field in your ${chalk.cyan('package.json')}.`
      );
Dan Abramov's avatar
Dan Abramov committed
116
      console.log();
117
118
      console.log(`The ${chalk.cyan('build')} folder is ready to be deployed.`);
      console.log(`To publish it at ${chalk.green(publicUrl)}, run:`);
119
120
121
122
      // If script deploy has been added to package.json, skip the instructions
      if (typeof appPackage.scripts.deploy === 'undefined') {
        console.log();
        if (useYarn) {
123
          console.log(`  ${chalk.cyan('yarn')} add --dev gh-pages`);
124
        } else {
125
          console.log(`  ${chalk.cyan('npm')} install --save-dev gh-pages`);
126
127
        }
        console.log();
128
129
130
        console.log(
          `Add the following script in your ${chalk.cyan('package.json')}.`
        );
131
        console.log();
132
133
134
135
136
137
138
139
140
        console.log(`    ${chalk.dim('// ...')}`);
        console.log(`    ${chalk.yellow('"scripts"')}: {`);
        console.log(`      ${chalk.dim('// ...')}`);
        console.log(
          `      ${chalk.yellow('"predeploy"')}: ${chalk.yellow('"npm run build",')}`
        );
        console.log(
          `      ${chalk.yellow('"deploy"')}: ${chalk.yellow('"gh-pages -d build"')}`
        );
141
142
143
        console.log('    }');
        console.log();
        console.log('Then run:');
Ville Immonen's avatar
Ville Immonen committed
144
      }
145
      console.log();
146
      console.log(`  ${chalk.cyan(useYarn ? 'yarn' : 'npm')} run deploy`);
Elijah Manor's avatar
Elijah Manor committed
147
      console.log();
Dan Abramov's avatar
Dan Abramov committed
148
149
    } else if (publicPath !== '/') {
      // "homepage": "http://mywebsite.com/project"
150
151
152
153
154
155
      console.log(
        `The project was built assuming it is hosted at ${chalk.green(publicPath)}.`
      );
      console.log(
        `You can control this with the ${chalk.green('homepage')} field in your ${chalk.cyan('package.json')}.`
      );
Elijah Manor's avatar
Elijah Manor committed
156
      console.log();
157
      console.log(`The ${chalk.cyan('build')} folder is ready to be deployed.`);
Elijah Manor's avatar
Elijah Manor committed
158
      console.log();
Dan Abramov's avatar
Dan Abramov committed
159
    } else {
160
      if (publicUrl) {
Dan Abramov's avatar
Dan Abramov committed
161
        // "homepage": "http://mywebsite.com"
162
163
164
165
166
167
        console.log(
          `The project was built assuming it is hosted at ${chalk.green(publicUrl)}.`
        );
        console.log(
          `You can control this with the ${chalk.green('homepage')} field in your ${chalk.cyan('package.json')}.`
        );
Dan Abramov's avatar
Dan Abramov committed
168
        console.log();
Dan Abramov's avatar
Dan Abramov committed
169
170
      } else {
        // no homepage
171
172
173
174
175
176
177
        console.log(
          'The project was built assuming it is hosted at the server root.'
        );
        console.log(
          `To override this, specify the ${chalk.green('homepage')} in your ${chalk.cyan('package.json')}.`
        );
        console.log('For example, add this to build it for GitHub Pages:');
Dan Abramov's avatar
Dan Abramov committed
178
        console.log();
179
180
181
        console.log(
          `  ${chalk.green('"homepage"')} ${chalk.cyan(':')} ${chalk.green('"http://myname.github.io/myapp"')}${chalk.cyan(',')}`
        );
Dan Abramov's avatar
Dan Abramov committed
182
        console.log();
Dan Abramov's avatar
Dan Abramov committed
183
      }
184
185
      const build = path.relative(process.cwd(), paths.appBuild);
      console.log(`The ${chalk.cyan(build)} folder is ready to be deployed.`);
186
      console.log('You may serve it with a static server:');
Dan Abramov's avatar
Dan Abramov committed
187
      console.log();
Ville Immonen's avatar
Ville Immonen committed
188
      if (useYarn) {
189
        console.log(`  ${chalk.cyan('yarn')} global add serve`);
Ville Immonen's avatar
Ville Immonen committed
190
      } else {
191
        console.log(`  ${chalk.cyan('npm')} install -g serve`);
Ville Immonen's avatar
Ville Immonen committed
192
      }
193
      console.log(`  ${chalk.cyan('serve')} -s build`);
Dan Abramov's avatar
Dan Abramov committed
194
      console.log();
Elijah Manor's avatar
Elijah Manor committed
195
196
197
    }
  });
}
198
199
200
201

function copyPublicFolder() {
  fs.copySync(paths.appPublic, paths.appBuild, {
    dereference: true,
202
    filter: file => file !== paths.appHtml,
203
204
  });
}