UNPKG

13.5 kBJavaScriptView Raw
1// @remove-on-eject-begin
2/**
3 * Copyright (c) 2015-present, Facebook, Inc.
4 * All rights reserved.
5 *
6 * This source code is licensed under the BSD-style license found in the
7 * LICENSE file in the root directory of this source tree. An additional grant
8 * of patent rights can be found in the PATENTS file in the same directory.
9 */
10// @remove-on-eject-end
11
12process.env.NODE_ENV = 'development';
13
14// Load environment variables from .env file. Suppress warnings using silent
15// if this file is missing. dotenv will never modify any environment variables
16// that have already been set.
17// https://github.com/motdotla/dotenv
18require('dotenv').config({silent: true});
19
20var chalk = require('chalk');
21var webpack = require('webpack');
22var WebpackDevServer = require('webpack-dev-server');
23var historyApiFallback = require('connect-history-api-fallback');
24var httpProxyMiddleware = require('http-proxy-middleware');
25var detect = require('detect-port');
26var clearConsole = require('react-dev-utils/clearConsole');
27var checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
28var formatWebpackMessages = require('react-dev-utils/formatWebpackMessages');
29var getProcessForPort = require('react-dev-utils/getProcessForPort');
30var openBrowser = require('react-dev-utils/openBrowser');
31var prompt = require('react-dev-utils/prompt');
32var fs = require('fs');
33var config = require('../config/webpack.config.dev');
34var paths = require('../config/paths');
35
36var useYarn = fs.existsSync(paths.yarnLockFile);
37var cli = useYarn ? 'yarn' : 'npm';
38var isInteractive = process.stdout.isTTY;
39
40// Warn and crash if required files are missing
41if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
42 process.exit(1);
43}
44
45// Tools like Cloud9 rely on this.
46var DEFAULT_PORT = process.env.PORT || 3000;
47var compiler;
48var handleCompile;
49
50// You can safely remove this after ejecting.
51// We only use this block for testing of Create React App itself:
52var isSmokeTest = process.argv.some(arg => arg.indexOf('--smoke-test') > -1);
53if (isSmokeTest) {
54 handleCompile = function (err, stats) {
55 if (err || stats.hasErrors() || stats.hasWarnings()) {
56 process.exit(1);
57 } else {
58 process.exit(0);
59 }
60 };
61}
62
63function setupCompiler(host, port, protocol) {
64 // "Compiler" is a low-level interface to Webpack.
65 // It lets us listen to some events and provide our own custom messages.
66 compiler = webpack(config, handleCompile);
67
68 // "invalid" event fires when you have changed a file, and Webpack is
69 // recompiling a bundle. WebpackDevServer takes care to pause serving the
70 // bundle, so if you refresh, it'll wait instead of serving the old one.
71 // "invalid" is short for "bundle invalidated", it doesn't imply any errors.
72 compiler.plugin('invalid', function() {
73 if (isInteractive) {
74 clearConsole();
75 }
76 console.log('Compiling...');
77 });
78
79 var isFirstCompile = true;
80
81 // "done" event fires when Webpack has finished recompiling the bundle.
82 // Whether or not you have warnings or errors, you will get this event.
83 compiler.plugin('done', function(stats) {
84 if (isInteractive) {
85 clearConsole();
86 }
87
88 // We have switched off the default Webpack output in WebpackDevServer
89 // options so we are going to "massage" the warnings and errors and present
90 // them in a readable focused way.
91 var messages = formatWebpackMessages(stats.toJson({}, true));
92 var isSuccessful = !messages.errors.length && !messages.warnings.length;
93 var showInstructions = isSuccessful && (isInteractive || isFirstCompile);
94
95 if (isSuccessful) {
96 console.log(chalk.green('Compiled successfully!'));
97 }
98
99 if (showInstructions) {
100 console.log();
101 console.log('The app is running at:');
102 console.log();
103 console.log(' ' + chalk.cyan(protocol + '://' + host + ':' + port + '/'));
104 console.log();
105 console.log('Note that the development build is not optimized.');
106 console.log('To create a production build, use ' + chalk.cyan(cli + ' run build') + '.');
107 console.log();
108 isFirstCompile = false;
109 }
110
111 // If errors exist, only show errors.
112 if (messages.errors.length) {
113 console.log(chalk.red('Failed to compile.'));
114 console.log();
115 messages.errors.forEach(message => {
116 console.log(message);
117 console.log();
118 });
119 return;
120 }
121
122 // Show warnings if no errors were found.
123 if (messages.warnings.length) {
124 console.log(chalk.yellow('Compiled with warnings.'));
125 console.log();
126 messages.warnings.forEach(message => {
127 console.log(message);
128 console.log();
129 });
130 // Teach some ESLint tricks.
131 console.log('You may use special comments to disable some warnings.');
132 console.log('Use ' + chalk.yellow('// eslint-disable-next-line') + ' to ignore the next line.');
133 console.log('Use ' + chalk.yellow('/* eslint-disable */') + ' to ignore all warnings in a file.');
134 // Teach some TSLint tricks.
135 console.log('Use ' + chalk.yellow('tslint:disable-line') + ' to disable this line.');
136 console.log('Use ' + chalk.yellow('tslint:disable-next-line') + ' to ignore the rules on next line.');
137 console.log('Use ' + chalk.yellow('tslint:disable ') + ' to disable linting for rest of file.');
138 console.log('Use ' + chalk.yellow('tslint:enable ') + ' to enable linting for rest of file.');
139 }
140 });
141}
142
143// We need to provide a custom onError function for httpProxyMiddleware.
144// It allows us to log custom error messages on the console.
145function onProxyError(proxy) {
146 return function(err, req, res){
147 var host = req.headers && req.headers.host;
148 console.log(
149 chalk.red('Proxy error:') + ' Could not proxy request ' + chalk.cyan(req.url) +
150 ' from ' + chalk.cyan(host) + ' to ' + chalk.cyan(proxy) + '.'
151 );
152 console.log(
153 'See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (' +
154 chalk.cyan(err.code) + ').'
155 );
156 console.log();
157
158 // And immediately send the proper error response to the client.
159 // Otherwise, the request will eventually timeout with ERR_EMPTY_RESPONSE on the client side.
160 if (res.writeHead && !res.headersSent) {
161 res.writeHead(500);
162 }
163 res.end('Proxy error: Could not proxy request ' + req.url + ' from ' +
164 host + ' to ' + proxy + ' (' + err.code + ').'
165 );
166 }
167}
168
169function addMiddleware(devServer) {
170 // `proxy` lets you to specify a fallback server during development.
171 // Every unrecognized request will be forwarded to it.
172 var proxy = require(paths.appPackageJson).proxy;
173 devServer.use(historyApiFallback({
174 // Paths with dots should still use the history fallback.
175 // See https://github.com/facebookincubator/create-react-app/issues/387.
176 disableDotRule: true,
177 // For single page apps, we generally want to fallback to /index.html.
178 // However we also want to respect `proxy` for API calls.
179 // So if `proxy` is specified, we need to decide which fallback to use.
180 // We use a heuristic: if request `accept`s text/html, we pick /index.html.
181 // Modern browsers include text/html into `accept` header when navigating.
182 // However API calls like `fetch()` won’t generally accept text/html.
183 // If this heuristic doesn’t work well for you, don’t use `proxy`.
184 htmlAcceptHeaders: proxy ?
185 ['text/html'] :
186 ['text/html', '*/*']
187 }));
188 if (proxy) {
189 if (typeof proxy !== 'string') {
190 console.log(chalk.red('When specified, "proxy" in package.json must be a string.'));
191 console.log(chalk.red('Instead, the type of "proxy" was "' + typeof proxy + '".'));
192 console.log(chalk.red('Either remove "proxy" from package.json, or make it a string.'));
193 process.exit(1);
194 }
195
196 // Otherwise, if proxy is specified, we will let it handle any request.
197 // There are a few exceptions which we won't send to the proxy:
198 // - /index.html (served as HTML5 history API fallback)
199 // - /*.hot-update.json (WebpackDevServer uses this too for hot reloading)
200 // - /sockjs-node/* (WebpackDevServer uses this for hot reloading)
201 // Tip: use https://jex.im/regulex/ to visualize the regex
202 var mayProxy = /^(?!\/(index\.html$|.*\.hot-update\.json$|sockjs-node\/)).*$/;
203
204 // Pass the scope regex both to Express and to the middleware for proxying
205 // of both HTTP and WebSockets to work without false positives.
206 var hpm = httpProxyMiddleware(pathname => mayProxy.test(pathname), {
207 target: proxy,
208 logLevel: 'silent',
209 onProxyReq: function(proxyReq, req, res) {
210 // Browers may send Origin headers even with same-origin
211 // requests. To prevent CORS issues, we have to change
212 // the Origin to match the target URL.
213 if (proxyReq.getHeader('origin')) {
214 proxyReq.setHeader('origin', proxy);
215 }
216 },
217 onError: onProxyError(proxy),
218 secure: false,
219 changeOrigin: true,
220 ws: true
221 });
222 devServer.use(mayProxy, hpm);
223
224 // Listen for the websocket 'upgrade' event and upgrade the connection.
225 // If this is not done, httpProxyMiddleware will not try to upgrade until
226 // an initial plain HTTP request is made.
227 devServer.listeningApp.on('upgrade', hpm.upgrade);
228 }
229
230 // Finally, by now we have certainly resolved the URL.
231 // It may be /index.html, so let the dev server try serving it again.
232 devServer.use(devServer.middleware);
233}
234
235function runDevServer(host, port, protocol) {
236 var devServer = new WebpackDevServer(compiler, {
237 // Enable gzip compression of generated files.
238 compress: true,
239 // Silence WebpackDevServer's own logs since they're generally not useful.
240 // It will still show compile warnings and errors with this setting.
241 clientLogLevel: 'none',
242 // By default WebpackDevServer serves physical files from current directory
243 // in addition to all the virtual build products that it serves from memory.
244 // This is confusing because those files won’t automatically be available in
245 // production build folder unless we copy them. However, copying the whole
246 // project directory is dangerous because we may expose sensitive files.
247 // Instead, we establish a convention that only files in `public` directory
248 // get served. Our build script will copy `public` into the `build` folder.
249 // In `index.html`, you can get URL of `public` folder with %PUBLIC_URL%:
250 // <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
251 // In JavaScript code, you can access it with `process.env.PUBLIC_URL`.
252 // Note that we only recommend to use `public` folder as an escape hatch
253 // for files like `favicon.ico`, `manifest.json`, and libraries that are
254 // for some reason broken when imported through Webpack. If you just want to
255 // use an image, put it in `src` and `import` it from JavaScript instead.
256 contentBase: paths.appPublic,
257 // Enable hot reloading server. It will provide /sockjs-node/ endpoint
258 // for the WebpackDevServer client so it can learn when the files were
259 // updated. The WebpackDevServer client is included as an entry point
260 // in the Webpack development configuration. Note that only changes
261 // to CSS are currently hot reloaded. JS changes will refresh the browser.
262 hot: true,
263 // It is important to tell WebpackDevServer to use the same "root" path
264 // as we specified in the config. In development, we always serve from /.
265 publicPath: config.output.publicPath,
266 // WebpackDevServer is noisy by default so we emit custom message instead
267 // by listening to the compiler events with `compiler.plugin` calls above.
268 quiet: true,
269 // Reportedly, this avoids CPU overload on some systems.
270 // https://github.com/facebookincubator/create-react-app/issues/293
271 watchOptions: {
272 ignored: /node_modules/
273 },
274 // Enable HTTPS if the HTTPS environment variable is set to 'true'
275 https: protocol === "https",
276 host: host
277 });
278
279 // Our custom middleware proxies requests to /index.html or a remote API.
280 addMiddleware(devServer);
281
282 // Launch WebpackDevServer.
283 devServer.listen(port, (err, result) => {
284 if (err) {
285 return console.log(err);
286 }
287
288 if (isInteractive) {
289 clearConsole();
290 }
291 console.log(chalk.cyan('Starting the development server...'));
292 console.log();
293
294 openBrowser(protocol + '://' + host + ':' + port + '/');
295 });
296}
297
298function run(port) {
299 var protocol = process.env.HTTPS === 'true' ? "https" : "http";
300 var host = process.env.HOST || 'localhost';
301 setupCompiler(host, port, protocol);
302 runDevServer(host, port, protocol);
303}
304
305// We attempt to use the default port but if it is busy, we offer the user to
306// run on a different port. `detect()` Promise resolves to the next free port.
307detect(DEFAULT_PORT).then(port => {
308 if (port === DEFAULT_PORT) {
309 run(port);
310 return;
311 }
312
313 if (isInteractive) {
314 clearConsole();
315 var existingProcess = getProcessForPort(DEFAULT_PORT);
316 var question =
317 chalk.yellow('Something is already running on port ' + DEFAULT_PORT + '.' +
318 ((existingProcess) ? ' Probably:\n ' + existingProcess : '')) +
319 '\n\nWould you like to run the app on another port instead?';
320
321 prompt(question, true).then(shouldChangePort => {
322 if (shouldChangePort) {
323 run(port);
324 }
325 });
326 } else {
327 console.log(chalk.red('Something is already running on port ' + DEFAULT_PORT + '.'));
328 }
329});