diff --git a/config/paths.js b/config/paths.js index 751dd685..c09ef154 100644 --- a/config/paths.js +++ b/config/paths.js @@ -8,4 +8,4 @@ module.exports = { ownModules: path.resolve(__dirname, '../node_modules'), scripts: path.resolve(__dirname, '../scripts'), elmMake: path.resolve(__dirname, '../node_modules/.bin/elm-make') -}; \ No newline at end of file +}; diff --git a/package.json b/package.json index 04c79916..0d3e27f0 100644 --- a/package.json +++ b/package.json @@ -43,6 +43,7 @@ "chalk": "1.1.3", "clean-webpack-plugin": "0.1.14", "cli-table": "0.3.1", + "connect-history-api-fallback": "^1.3.0", "cross-spawn": "5.0.1", "css-loader": "0.26.1", "dotenv": "^2.0.0", @@ -55,6 +56,7 @@ "file-loader": "0.9.0", "fs-extra": "1.0.0", "html-webpack-plugin": "2.24.1", + "http-proxy-middleware": "^0.17.3", "minimist": "1.2.0", "path-exists": "3.0.0", "postcss-loader": "1.2.1", diff --git a/scripts/start.js b/scripts/start.js index fa7cd480..dbe4cf9b 100644 --- a/scripts/start.js +++ b/scripts/start.js @@ -1,8 +1,4 @@ -process.env.NODE_ENV = 'development'; -// Load environment variables from .env file. -// Suppress warnings if this file is missing. -require('dotenv').config({silent: true}); - +const fs = require('fs'); const pathExists = require('path-exists'); const chalk = require('chalk'); const webpack = require('webpack'); @@ -11,6 +7,12 @@ const config = require('../config/webpack.config.dev'); const formatWebpackMessages = require('react-dev-utils/formatWebpackMessages'); const clearConsole = require('react-dev-utils/clearConsole'); const openBrowser = require('react-dev-utils/openBrowser'); +const historyApiFallback = require('connect-history-api-fallback'); +const httpProxyMiddleware = require('http-proxy-middleware'); + +// Load environment variables from .env file. +// Suppress warnings if this file is missing. +require('dotenv').config({silent: true}); if (pathExists.sync('elm-package.json') === false) { console.log('Please, run the build script from project root directory'); @@ -54,14 +56,108 @@ compiler.plugin('done', function (stats) { } }); + +// We need to provide a custom onError function for httpProxyMiddleware. +// It allows us to log custom error messages on the console. +function onProxyError(proxy) { + return function(err, req, res){ + var host = req.headers && req.headers.host; + console.log( + chalk.red('Proxy error:') + ' Could not proxy request ' + chalk.cyan(req.url) + + ' from ' + chalk.cyan(host) + ' to ' + chalk.cyan(proxy) + '.' + ); + console.log( + 'See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (' + + chalk.cyan(err.code) + ').' + ); + console.log(); + + // And immediately send the proper error response to the client. + // Otherwise, the request will eventually timeout with ERR_EMPTY_RESPONSE on the client side. + if (res.writeHead && !res.headersSent) { + res.writeHead(500); + } + res.end('Proxy error: Could not proxy request ' + req.url + ' from ' + + host + ' to ' + proxy + ' (' + err.code + ').' + ); + }; +} + +function addMiddleware(devServer) { + // `proxy` lets you to specify a fallback server during development. + // Every unrecognized request will be forwarded to it. + var proxy = JSON.parse(fs.readFileSync('elm-package.json', 'utf-8')).proxy; + devServer.use(historyApiFallback({ + // Paths with dots should still use the history fallback. + // See https://github.com/facebookincubator/create-react-app/issues/387. + disableDotRule: true, + // For single page apps, we generally want to fallback to /index.html. + // However we also want to respect `proxy` for API calls. + // So if `proxy` is specified, we need to decide which fallback to use. + // We use a heuristic: if request `accept`s text/html, we pick /index.html. + // Modern browsers include text/html into `accept` header when navigating. + // However API calls like `fetch()` won’t generally accept text/html. + // If this heuristic doesn’t work well for you, don’t use `proxy`. + htmlAcceptHeaders: proxy ? + [ 'text/html' ] : + [ 'text/html', '*/*' ] + })); + if (proxy) { + if (typeof proxy !== 'string') { + console.log(chalk.red('When specified, "proxy" in package.json must be a string.')); + console.log(chalk.red('Instead, the type of "proxy" was "' + typeof proxy + '".')); + console.log(chalk.red('Either remove "proxy" from package.json, or make it a string.')); + process.exit(1); + } + + // Otherwise, if proxy is specified, we will let it handle any request. + // There are a few exceptions which we won't send to the proxy: + // - /index.html (served as HTML5 history API fallback) + // - /*.hot-update.json (WebpackDevServer uses this too for hot reloading) + // - /sockjs-node/* (WebpackDevServer uses this for hot reloading) + // Tip: use https://jex.im/regulex/ to visualize the regex + var mayProxy = /^(?!\/(index\.html$|.*\.hot-update\.json$|sockjs-node\/)).*$/; + + // Pass the scope regex both to Express and to the middleware for proxying + // of both HTTP and WebSockets to work without false positives. + var hpm = httpProxyMiddleware(pathname => mayProxy.test(pathname), { + target: proxy, + logLevel: 'silent', + onProxyReq: function(proxyReq) { + // Browers may send Origin headers even with same-origin + // requests. To prevent CORS issues, we have to change + // the Origin to match the target URL. + if (proxyReq.getHeader('origin')) { + proxyReq.setHeader('origin', proxy); + } + }, + onError: onProxyError(proxy), + secure: false, + changeOrigin: true, + ws: true + }); + devServer.use(mayProxy, hpm); + + // Listen for the websocket 'upgrade' event and upgrade the connection. + // If this is not done, httpProxyMiddleware will not try to upgrade until + // an initial plain HTTP request is made. + devServer.listeningApp.on('upgrade', hpm.upgrade); + } + + // Finally, by now we have certainly resolved the URL. + // It may be /index.html, so let the dev server try serving it again. + devServer.use(devServer.middleware); +} + const devServer = new WebpackDevServer(compiler, { hot: true, inline: true, publicPath: '/', - quiet: true, - historyApiFallback: true, + quiet: true }); +addMiddleware(devServer); + // Launch WebpackDevServer. devServer.listen(port, function (err) { if (err) { diff --git a/yarn.lock b/yarn.lock index 3c347701..91705a8d 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1584,7 +1584,7 @@ http-errors@~1.5.0: setprototypeof "1.0.2" statuses ">= 1.3.1 < 2" -http-proxy-middleware@~0.17.1: +http-proxy-middleware@^0.17.3, http-proxy-middleware@~0.17.1: version "0.17.3" resolved "https://registry.yarnpkg.com/http-proxy-middleware/-/http-proxy-middleware-0.17.3.tgz#940382147149b856084f5534752d5b5a8168cd1d" dependencies: