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