start.js 5.38 KB
Newer Older
Christopher Chedeau's avatar
Christopher Chedeau committed
1
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
11
process.env.NODE_ENV = 'development';

12
var path = require('path');
13
var chalk = require('chalk');
Dan Abramov's avatar
Dan Abramov committed
14
15
var webpack = require('webpack');
var WebpackDevServer = require('webpack-dev-server');
Christopher Chedeau's avatar
.    
Christopher Chedeau committed
16
var execSync = require('child_process').execSync;
17
var opn = require('opn');
18
var detect = require('./utils/detectPort');
19
20
21
var prompt = require('./utils/prompt');
var config = require('../config/webpack.config.dev');

Dan Abramov's avatar
Dan Abramov committed
22
23
// Tools like Cloud9 rely on this
var DEFAULT_PORT = process.env.PORT || 3000;
24
var compiler;
Dan Abramov's avatar
Dan Abramov committed
25

26
27
// TODO: hide this behind a flag and eliminate dead code on eject.
// This shouldn't be exposed to the user.
Dan Abramov's avatar
Dan Abramov committed
28
var handleCompile;
29
var isSmokeTest = process.argv.some(arg => arg.indexOf('--smoke-test') > -1);
Dan Abramov's avatar
Dan Abramov committed
30
if (isSmokeTest) {
Dan Abramov's avatar
Dan Abramov committed
31
  handleCompile = function (err, stats) {
32
    if (err || stats.hasErrors() || stats.hasWarnings()) {
Dan Abramov's avatar
Dan Abramov committed
33
34
35
36
37
38
39
      process.exit(1);
    } else {
      process.exit(0);
    }
  };
}

40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
var friendlySyntaxErrorLabel = 'Syntax error:';

function isLikelyASyntaxError(message) {
  return message.indexOf(friendlySyntaxErrorLabel) !== -1;
}

// This is a little hacky.
// It would be easier if webpack provided a rich error object.

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
63
    .replace(/^\s*at\s.*:\d+:\d+[\s\)]*\n/gm, '') // at ... ...:x:y
64
65
66
67
    // Webpack loader names obscure CSS filenames
    .replace('./~/css-loader!./~/postcss-loader!', '');
}

68
function clearConsole() {
69
  process.stdout.write('\x1bc');
70
}
71

72
73
function setupCompiler(port) {
  compiler = webpack(config, handleCompile);
74

75
76
77
78
  compiler.plugin('invalid', function() {
    clearConsole();
    console.log('Compiling...');
  });
79

80
81
82
83
84
85
  compiler.plugin('done', function(stats) {
    clearConsole();
    var hasErrors = stats.hasErrors();
    var hasWarnings = stats.hasWarnings();
    if (!hasErrors && !hasWarnings) {
      console.log(chalk.green('Compiled successfully!'));
86
      console.log();
87
88
89
90
      console.log('The app is running at http://localhost:' + port + '/');
      console.log();
      return;
    }
91

92
93
94
95
96
97
98
99
100
101
    var json = stats.toJson();
    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.'));
102
      console.log();
103
104
105
106
107
108
109
110
111
112
113
114
115
      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;
    }
116

117
118
119
120
121
122
123
124
125
126
127
128
129
130
    if (hasWarnings) {
      console.log(chalk.yellow('Compiled with warnings.'));
      console.log();
      formattedWarnings.forEach(message => {
        console.log(message);
        console.log();
      });

      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.');
    }
  });
}
131

132
function openBrowser(port) {
133
134
135
136
137
138
139
  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(
        'osascript ' +
140
141
        path.resolve(__dirname, './utils/chrome.applescript') +
        ' http://localhost:' + port + '/'
142
143
144
145
146
147
148
149
      );
      return;
    } catch (err) {
      // Ignore errors.
    }
  }
  // Fallback to opn
  // (It will always open new tab)
150
151
152
153
154
155
156
157
  opn('http://localhost:' + port + '/');
}

function runDevServer(port) {
  new WebpackDevServer(compiler, {
    historyApiFallback: true,
    hot: true, // Note: only CSS is currently hot reloaded
    publicPath: config.output.publicPath,
158
159
160
161
    quiet: true,
    watchOptions: {
      ignored: /node_modules/
    }
162
163
164
165
166
167
168
169
170
171
  }).listen(port, (err, result) => {
    if (err) {
      return console.log(err);
    }

    clearConsole();
    console.log(chalk.cyan('Starting the development server...'));
    console.log();
    openBrowser(port);
  });
172
173
}

174
175
176
177
178
179
180
181
182
function run(port) {
  setupCompiler(port);
  runDevServer(port);
}

detect(DEFAULT_PORT).then(port => {
  if (port === DEFAULT_PORT) {
    run(port);
    return;
Dan Abramov's avatar
Dan Abramov committed
183
  }
Christopher Chedeau's avatar
.    
Christopher Chedeau committed
184

Dan Abramov's avatar
Dan Abramov committed
185
  clearConsole();
186
187
188
189
190
191
192
193
194
  var question =
    chalk.yellow('Something is already running at port ' + DEFAULT_PORT + '.') +
    '\n\nWould you like to run the app at another port instead?';

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