Guest User

Untitled

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