start.js 12 KB

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