start.js 11.8 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';

14
var path = require('path');
15
var chalk = require('chalk');
Dan Abramov's avatar
Dan Abramov committed
16
17
var webpack = require('webpack');
var WebpackDevServer = require('webpack-dev-server');
18
19
var historyApiFallback = require('connect-history-api-fallback');
var httpProxyMiddleware = require('http-proxy-middleware');
Christopher Chedeau's avatar
.    
Christopher Chedeau committed
20
var execSync = require('child_process').execSync;
21
var opn = require('opn');
22
var detect = require('detect-port');
23
24
var prompt = require('./utils/prompt');
var config = require('../config/webpack.config.dev');
25
var paths = require('../config/paths');
26

27
// Tools like Cloud9 rely on this.
Dan Abramov's avatar
Dan Abramov committed
28
var DEFAULT_PORT = process.env.PORT || 3000;
29
var compiler;
Dan Abramov's avatar
Dan Abramov committed
30
var handleCompile;
31
32
33

// You can safely remove this after ejecting.
// We only use this block for testing of Create React App itself:
34
var isSmokeTest = process.argv.some(arg => arg.indexOf('--smoke-test') > -1);
Dan Abramov's avatar
Dan Abramov committed
35
if (isSmokeTest) {
Dan Abramov's avatar
Dan Abramov committed
36
  handleCompile = function (err, stats) {
37
    if (err || stats.hasErrors() || stats.hasWarnings()) {
Dan Abramov's avatar
Dan Abramov committed
38
39
40
41
42
43
44
      process.exit(1);
    } else {
      process.exit(0);
    }
  };
}

45
46
47
// Some custom utilities to prettify Webpack output.
// This is a little hacky.
// It would be easier if webpack provided a rich error object.
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
var friendlySyntaxErrorLabel = 'Syntax error:';
function isLikelyASyntaxError(message) {
  return message.indexOf(friendlySyntaxErrorLabel) !== -1;
}
function formatMessage(message) {
  return message
    // Make some common errors shorter:
    .replace(
      // Babel syntax error
      'Module build failed: SyntaxError:',
      friendlySyntaxErrorLabel
    )
    .replace(
      // Webpack file not found error
      /Module not found: Error: Cannot resolve 'file' or 'directory'/,
      'Module not found:'
    )
    // Internal stacks are generally useless so we strip them
Dan Abramov's avatar
Dan Abramov committed
66
    .replace(/^\s*at\s.*:\d+:\d+[\s\)]*\n/gm, '') // at ... ...:x:y
67
68
69
70
    // Webpack loader names obscure CSS filenames
    .replace('./~/css-loader!./~/postcss-loader!', '');
}

71
function clearConsole() {
72
73
  // This seems to work best on Windows and other systems.
  // The intention is to clear the output so you can focus on most recent build.
74
  process.stdout.write('\x1bc');
75
}
76

77
function setupCompiler(port, protocol) {
78
79
  // "Compiler" is a low-level interface to Webpack.
  // It lets us listen to some events and provide our own custom messages.
80
  compiler = webpack(config, handleCompile);
81

82
83
84
85
  // "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.
86
87
88
89
  compiler.plugin('invalid', function() {
    clearConsole();
    console.log('Compiling...');
  });
90

91
92
  // "done" event fires when Webpack has finished recompiling the bundle.
  // Whether or not you have warnings or errors, you will get this event.
93
94
95
96
97
98
  compiler.plugin('done', function(stats) {
    clearConsole();
    var hasErrors = stats.hasErrors();
    var hasWarnings = stats.hasWarnings();
    if (!hasErrors && !hasWarnings) {
      console.log(chalk.green('Compiled successfully!'));
99
      console.log();
100
      console.log('The app is running at:');
101
      console.log();
102
      console.log('  ' + chalk.cyan(protocol + '://localhost:' + port + '/'));
103
104
105
106
      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();
107
108
      return;
    }
109

110
111
112
    // 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.
113
114
115
    // We use stats.toJson({}, true) to make output more compact and readable:
    // https://github.com/facebookincubator/create-react-app/issues/401#issuecomment-238291901
    var json = stats.toJson({}, true);
116
117
118
119
120
121
122
123
    var formattedErrors = json.errors.map(message =>
      'Error in ' + formatMessage(message)
    );
    var formattedWarnings = json.warnings.map(message =>
      'Warning in ' + formatMessage(message)
    );
    if (hasErrors) {
      console.log(chalk.red('Failed to compile.'));
124
      console.log();
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
      if (formattedErrors.some(isLikelyASyntaxError)) {
        // If there are any syntax errors, show just them.
        // This prevents a confusing ESLint parsing error
        // preceding a much more useful Babel syntax error.
        formattedErrors = formattedErrors.filter(isLikelyASyntaxError);
      }
      formattedErrors.forEach(message => {
        console.log(message);
        console.log();
      });
      // If errors exist, ignore warnings.
      return;
    }
    if (hasWarnings) {
      console.log(chalk.yellow('Compiled with warnings.'));
      console.log();
      formattedWarnings.forEach(message => {
        console.log(message);
        console.log();
      });
145
      // Teach some ESLint tricks.
146
147
148
149
150
151
      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.');
    }
  });
}
152

153
function openBrowser(port, protocol) {
154
155
156
157
158
159
  if (process.platform === 'darwin') {
    try {
      // Try our best to reuse existing tab
      // on OS X Google Chrome with AppleScript
      execSync('ps cax | grep "Google Chrome"');
      execSync(
160
        'osascript chrome.applescript ' + protocol + '://localhost:' + port + '/',
161
        {cwd: path.join(__dirname, 'utils'), stdio: 'ignore'}
162
163
164
165
166
167
168
169
      );
      return;
    } catch (err) {
      // Ignore errors.
    }
  }
  // Fallback to opn
  // (It will always open new tab)
170
  opn(protocol + '://localhost:' + port + '/');
171
172
}

173
174
175
176
177
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({
178
179
    // Allow paths with dots in them to be loaded, reference issue #387
    disableDotRule: true,
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
    // 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.
    // However API calls like `fetch()` won’t generally won’t accept text/html.
    // 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)
Dan Abramov's avatar
Dan Abramov committed
204
    // Tip: use https://www.debuggex.com/ to visualize the regex
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
    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',
        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);
}

222
function runDevServer(port, protocol) {
223
  var devServer = new WebpackDevServer(compiler, {
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
    // By default WebpackDevServer also serves files from the current directory.
    // This might be useful in legacy apps. However we already encourage people
    // to use Webpack for importing assets in the code, so we don't need to
    // additionally serve files by their filenames. Otherwise, even if it
    // works in development, those files will be missing in production, unless
    // we explicitly copy them. But even if we copy the all the files into
    // the build output (which doesn't seem to be wise because it may contain
    // private information such as files with API keys, for example), we would
    // still have a problem. Since the filenames would be the same every time,
    // browsers would cache their content, and updating file content would not
    // work correctly. This is easily solved by importing assets through Webpack
    // because if it can then append content hashes to filenames in production,
    // just like it does for JS and CSS. And because we configured "html" loader
    // to be used for HTML files, even <link href="./src/something.png"> would
    // get resolved correctly by Webpack and handled both in development and
    // in production without actually serving it by that path.
    contentBase: [],
241
242
243
244
245
246
247
248
    // 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 /.
249
    publicPath: config.output.publicPath,
250
251
    // WebpackDevServer is noisy by default so we emit custom message instead
    // by listening to the compiler events with `compiler.plugin` calls above.
252
    quiet: true,
253
254
    // Reportedly, this avoids CPU overload on some systems.
    // https://github.com/facebookincubator/create-react-app/issues/293
255
256
    watchOptions: {
      ignored: /node_modules/
257
258
259
    },
    // Enable HTTPS if the HTTPS environment variable is set to 'true'
    https: protocol === "https" ? true : false
260
  });
261
262

  // Our custom middleware proxies requests to /index.html or a remote API.
263
  addMiddleware(devServer);
264
265

  // Launch WebpackDevServer.
266
  devServer.listen(port, (err, result) => {
267
268
269
270
271
272
273
    if (err) {
      return console.log(err);
    }

    clearConsole();
    console.log(chalk.cyan('Starting the development server...'));
    console.log();
274
    openBrowser(port, protocol);
275
  });
276
277
}

278
function run(port) {
279
280
281
  var protocol = process.env.HTTPS === 'true' ? "https" : "http";
  setupCompiler(port, protocol);
  runDevServer(port, protocol);
282
283
}

284
285
// 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.
286
287
288
289
detect(DEFAULT_PORT).then(port => {
  if (port === DEFAULT_PORT) {
    run(port);
    return;
Dan Abramov's avatar
Dan Abramov committed
290
  }
Christopher Chedeau's avatar
.    
Christopher Chedeau committed
291

Dan Abramov's avatar
Dan Abramov committed
292
  clearConsole();
293
  var question =
294
295
    chalk.yellow('Something is already running on port ' + DEFAULT_PORT + '.') +
    '\n\nWould you like to run the app on another port instead?';
296
297
298
299
300
301

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