build.js 7.26 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';

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

Brian Ng's avatar
Brian Ng committed
23
// Load environment variables from .env file. Suppress warnings using silent
24
25
26
// if this file is missing. dotenv will never modify any environment variables
// that have already been set.
// https://github.com/motdotla/dotenv
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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
42

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

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

Dan Abramov's avatar
Dan Abramov committed
55
  // Start the webpack build
56
  build(previousFileSizes);
57
58
59

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

62
63
64
65
66
67
68
69
70
71
// Print out errors
function printErrors(summary, errors) {
  console.log(chalk.red(summary));
  console.log();
  errors.forEach(err => {
    console.log(err.message || err);
    console.log();
  });
}

72
// Create the production build and print the deployment instructions.
73
function build(previousFileSizes) {
Elijah Manor's avatar
Elijah Manor committed
74
  console.log('Creating an optimized production build...');
75

76
  let compiler;
77
78
79
80
81
82
83
84
  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
85
    if (err) {
86
87
88
89
90
91
      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
92
      process.exit(1);
93
    }
94

95
    if (process.env.CI && stats.compilation.warnings.length) {
96
97
98
99
100
101
      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);
    }
102

Elijah Manor's avatar
Elijah Manor committed
103
    console.log(chalk.green('Compiled successfully.'));
104
    console.log();
Elijah Manor's avatar
Elijah Manor committed
105
106

    console.log('File sizes after gzip:');
107
    console.log();
108
    printFileSizesAfterBuild(stats, previousFileSizes);
109
    console.log();
Elijah Manor's avatar
Elijah Manor committed
110

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

function copyPublicFolder() {
  fs.copySync(paths.appPublic, paths.appBuild, {
    dereference: true,
209
    filter: file => file !== paths.appHtml,
210
211
  });
}