build.js 7.06 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;
});

23
24
// Ensure environment variables are read.
require('../config/env');
25
26
27
28
29
30
31
32
33
34
35
36
37
38

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
39

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

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

Dan Abramov's avatar
Dan Abramov committed
52
  // Start the webpack build
53
  build(previousFileSizes);
54
55
56

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

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

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

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

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

Elijah Manor's avatar
Elijah Manor committed
100
    console.log(chalk.green('Compiled successfully.'));
101
    console.log();
Elijah Manor's avatar
Elijah Manor committed
102
103

    console.log('File sizes after gzip:');
104
    console.log();
105
    printFileSizesAfterBuild(stats, previousFileSizes);
106
    console.log();
Elijah Manor's avatar
Elijah Manor committed
107

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

function copyPublicFolder() {
  fs.copySync(paths.appPublic, paths.appBuild, {
    dereference: true,
206
    filter: file => file !== paths.appHtml,
207
208
  });
}