start.js 11.3 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
Christopher Chedeau's avatar
Christopher Chedeau committed
11

12
13
process.env.NODE_ENV = 'development';

Brian Ng's avatar
Brian Ng committed
14
// Load environment variables from .env file. Suppress warnings using silent
15
16
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
require('dotenv').config({silent: true});

20
var chalk = require('chalk');
Dan Abramov's avatar
Dan Abramov committed
21
22
var webpack = require('webpack');
var WebpackDevServer = require('webpack-dev-server');
23
24
var historyApiFallback = require('connect-history-api-fallback');
var httpProxyMiddleware = require('http-proxy-middleware');
25
var detect = require('detect-port');
26
27
28
29
30
var clearConsole = require('react-dev-utils/clearConsole');
var checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
var formatWebpackMessages = require('react-dev-utils/formatWebpackMessages');
var openBrowser = require('react-dev-utils/openBrowser');
var prompt = require('react-dev-utils/prompt');
31
var config = require('../config/webpack.config.dev');
32
var paths = require('../config/paths');
33

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

39
// Tools like Cloud9 rely on this.
Dan Abramov's avatar
Dan Abramov committed
40
var DEFAULT_PORT = process.env.PORT || 3000;
41
var compiler;
Dan Abramov's avatar
Dan Abramov committed
42
var handleCompile;
43
44
45

// You can safely remove this after ejecting.
// We only use this block for testing of Create React App itself:
46
var isSmokeTest = process.argv.some(arg => arg.indexOf('--smoke-test') > -1);
Dan Abramov's avatar
Dan Abramov committed
47
if (isSmokeTest) {
Dan Abramov's avatar
Dan Abramov committed
48
  handleCompile = function (err, stats) {
49
    if (err || stats.hasErrors() || stats.hasWarnings()) {
Dan Abramov's avatar
Dan Abramov committed
50
51
52
53
54
55
56
      process.exit(1);
    } else {
      process.exit(0);
    }
  };
}

57
function setupCompiler(host, port, protocol) {
58
59
  // "Compiler" is a low-level interface to Webpack.
  // It lets us listen to some events and provide our own custom messages.
60
  compiler = webpack(config, handleCompile);
61

62
63
64
65
  // "invalid" event fires when you have changed a file, and Webpack is
  // recompiling a bundle. WebpackDevServer takes care to pause serving the
  // bundle, so if you refresh, it'll wait instead of serving the old one.
  // "invalid" is short for "bundle invalidated", it doesn't imply any errors.
66
67
68
69
  compiler.plugin('invalid', function() {
    clearConsole();
    console.log('Compiling...');
  });
70

71
72
  // "done" event fires when Webpack has finished recompiling the bundle.
  // Whether or not you have warnings or errors, you will get this event.
73
74
  compiler.plugin('done', function(stats) {
    clearConsole();
75
76
77
78

    // We have switched off the default Webpack output in WebpackDevServer
    // options so we are going to "massage" the warnings and errors and present
    // them in a readable focused way.
79
    var messages = formatWebpackMessages(stats.toJson({}, true));
80
    if (!messages.errors.length && !messages.warnings.length) {
81
      console.log(chalk.green('Compiled successfully!'));
82
      console.log();
83
      console.log('The app is running at:');
84
      console.log();
85
      console.log('  ' + chalk.cyan(protocol + '://' + host + ':' + port + '/'));
86
87
88
89
      console.log();
      console.log('Note that the development build is not optimized.');
      console.log('To create a production build, use ' + chalk.cyan('npm run build') + '.');
      console.log();
90
    }
91

92
93
    // If errors exist, only show errors.
    if (messages.errors.length) {
94
      console.log(chalk.red('Failed to compile.'));
95
      console.log();
96
      messages.errors.forEach(message => {
97
98
99
100
101
        console.log(message);
        console.log();
      });
      return;
    }
102
103
104

    // Show warnings if no errors were found.
    if (messages.warnings.length) {
105
106
      console.log(chalk.yellow('Compiled with warnings.'));
      console.log();
107
      messages.warnings.forEach(message => {
108
109
110
        console.log(message);
        console.log();
      });
111
      // Teach some ESLint tricks.
112
113
114
115
116
117
      console.log('You may use special comments to disable some warnings.');
      console.log('Use ' + chalk.yellow('// eslint-disable-next-line') + ' to ignore the next line.');
      console.log('Use ' + chalk.yellow('/* eslint-disable */') + ' to ignore all warnings in a file.');
    }
  });
}
118

119
120
121
122
123
124
125
126
127
128
// We need to provide a custom onError function for httpProxyMiddleware.
// It allows us to log custom error messages on the console.
function onProxyError(proxy) {
  return function(err, req, res){
    var host = req.headers && req.headers.host;
    console.log(
      chalk.red('Proxy error:') + ' Could not proxy request ' + chalk.cyan(req.url) +
      ' from ' + chalk.cyan(host) + ' to ' + chalk.cyan(proxy) + '.'
    );
    console.log(
129
      'See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (' +
130
131
132
      chalk.cyan(err.code) + ').'
    );
    console.log();
133
134
135
136
137
138

    // And immediately send the proper error response to the client.
    // Otherwise, the request will eventually timeout with ERR_EMPTY_RESPONSE on the client side.
    if (res.writeHead && !res.headersSent) {
        res.writeHead(500);
    }
139
    res.end('Proxy error: Could not proxy request ' + req.url + ' from ' +
140
141
      host + ' to ' + proxy + ' (' + err.code + ').'
    );
142
143
144
  }
}

145
146
147
148
149
function addMiddleware(devServer) {
  // `proxy` lets you to specify a fallback server during development.
  // Every unrecognized request will be forwarded to it.
  var proxy = require(paths.appPackageJson).proxy;
  devServer.use(historyApiFallback({
Dan Abramov's avatar
Dan Abramov committed
150
151
    // Paths with dots should still use the history fallback.
    // See https://github.com/facebookincubator/create-react-app/issues/387.
152
    disableDotRule: true,
153
154
155
156
157
    // For single page apps, we generally want to fallback to /index.html.
    // However we also want to respect `proxy` for API calls.
    // So if `proxy` is specified, we need to decide which fallback to use.
    // We use a heuristic: if request `accept`s text/html, we pick /index.html.
    // Modern browsers include text/html into `accept` header when navigating.
158
    // However API calls like `fetch()` won’t generally accept text/html.
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
    // If this heuristic doesn’t work well for you, don’t use `proxy`.
    htmlAcceptHeaders: proxy ?
      ['text/html'] :
      ['text/html', '*/*']
  }));
  if (proxy) {
    if (typeof proxy !== 'string') {
      console.log(chalk.red('When specified, "proxy" in package.json must be a string.'));
      console.log(chalk.red('Instead, the type of "proxy" was "' + typeof proxy + '".'));
      console.log(chalk.red('Either remove "proxy" from package.json, or make it a string.'));
      process.exit(1);
    }

    // Otherwise, if proxy is specified, we will let it handle any request.
    // There are a few exceptions which we won't send to the proxy:
    // - /index.html (served as HTML5 history API fallback)
    // - /*.hot-update.json (WebpackDevServer uses this too for hot reloading)
    // - /sockjs-node/* (WebpackDevServer uses this for hot reloading)
177
    // Tip: use https://jex.im/regulex/ to visualize the regex
178
179
180
181
182
183
184
    var mayProxy = /^(?!\/(index\.html$|.*\.hot-update\.json$|sockjs-node\/)).*$/;
    devServer.use(mayProxy,
      // Pass the scope regex both to Express and to the middleware for proxying
      // of both HTTP and WebSockets to work without false positives.
      httpProxyMiddleware(pathname => mayProxy.test(pathname), {
        target: proxy,
        logLevel: 'silent',
185
        onError: onProxyError(proxy),
186
187
188
189
190
191
192
193
194
195
        secure: false,
        changeOrigin: true
      })
    );
  }
  // Finally, by now we have certainly resolved the URL.
  // It may be /index.html, so let the dev server try serving it again.
  devServer.use(devServer.middleware);
}

196
function runDevServer(host, port, protocol) {
197
  var devServer = new WebpackDevServer(compiler, {
198
199
200
    // Silence WebpackDevServer's own logs since they're generally not useful.
    // It will still show compile warnings and errors with this setting.
    clientLogLevel: 'none',
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
    // By default WebpackDevServer serves physical files from current directory
    // in addition to all the virtual build products that it serves from memory.
    // This is confusing because those files won’t automatically be available in
    // production build folder unless we copy them. However, copying the whole
    // project directory is dangerous because we may expose sensitive files.
    // Instead, we establish a convention that only files in `public` directory
    // get served. Our build script will copy `public` into the `build` folder.
    // In `index.html`, you can get URL of `public` folder with %PUBLIC_PATH%:
    // <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
    // In JavaScript code, you can access it with `process.env.PUBLIC_URL`.
    // Note that we only recommend to use `public` folder as an escape hatch
    // for files like `favicon.ico`, `manifest.json`, and libraries that are
    // for some reason broken when imported through Webpack. If you just want to
    // use an image, put it in `src` and `import` it from JavaScript instead.
    contentBase: paths.appPublic,
216
217
218
219
220
221
222
223
    // Enable hot reloading server. It will provide /sockjs-node/ endpoint
    // for the WebpackDevServer client so it can learn when the files were
    // updated. The WebpackDevServer client is included as an entry point
    // in the Webpack development configuration. Note that only changes
    // to CSS are currently hot reloaded. JS changes will refresh the browser.
    hot: true,
    // It is important to tell WebpackDevServer to use the same "root" path
    // as we specified in the config. In development, we always serve from /.
224
    publicPath: config.output.publicPath,
225
226
    // WebpackDevServer is noisy by default so we emit custom message instead
    // by listening to the compiler events with `compiler.plugin` calls above.
227
    quiet: true,
228
229
    // Reportedly, this avoids CPU overload on some systems.
    // https://github.com/facebookincubator/create-react-app/issues/293
230
231
    watchOptions: {
      ignored: /node_modules/
232
233
    },
    // Enable HTTPS if the HTTPS environment variable is set to 'true'
234
    https: protocol === "https",
235
    host: host
236
  });
237
238

  // Our custom middleware proxies requests to /index.html or a remote API.
239
  addMiddleware(devServer);
240
241

  // Launch WebpackDevServer.
242
  devServer.listen(port, (err, result) => {
243
244
245
246
247
248
249
    if (err) {
      return console.log(err);
    }

    clearConsole();
    console.log(chalk.cyan('Starting the development server...'));
    console.log();
250
    openBrowser(protocol + '://' + host + ':' + port + '/');
251
  });
252
253
}

254
function run(port) {
255
  var protocol = process.env.HTTPS === 'true' ? "https" : "http";
256
257
258
  var host = process.env.HOST || 'localhost';
  setupCompiler(host, port, protocol);
  runDevServer(host, port, protocol);
259
260
}

261
262
// We attempt to use the default port but if it is busy, we offer the user to
// run on a different port. `detect()` Promise resolves to the next free port.
263
264
265
266
detect(DEFAULT_PORT).then(port => {
  if (port === DEFAULT_PORT) {
    run(port);
    return;
Dan Abramov's avatar
Dan Abramov committed
267
  }
Christopher Chedeau's avatar
.    
Christopher Chedeau committed
268

Dan Abramov's avatar
Dan Abramov committed
269
  clearConsole();
270
  var question =
271
272
    chalk.yellow('Something is already running on port ' + DEFAULT_PORT + '.') +
    '\n\nWould you like to run the app on another port instead?';
273
274
275
276
277
278

  prompt(question, true).then(shouldChangePort => {
    if (shouldChangePort) {
      run(port);
    }
  });
Dan Abramov's avatar
Dan Abramov committed
279
});