start.js 12 KB

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