From 1cbc6f7db62f78747cb6ca41450099181139325e Mon Sep 17 00:00:00 2001 From: Andrew Luca Date: Sun, 2 Feb 2020 13:55:26 +0200 Subject: [PATCH] feat(react-scripts): allow PUBLIC_URL in develoment mode (#7259) Co-authored-by: Eric Clemmons Co-authored-by: Alex Guerra Co-authored-by: Kelly Co-authored-by: Eric Clemmons Co-authored-by: Alex Guerra Co-authored-by: Kelly --- docusaurus/docs/advanced-configuration.md | 2 +- packages/react-dev-utils/README.md | 13 +- .../react-dev-utils/WebpackDevServerUtils.js | 6 +- .../__tests__/getPublicUrlOrPath.test.js | 128 ++++++++++++++++++ .../react-dev-utils/getPublicUrlOrPath.js | 65 +++++++++ .../noopServiceWorkerMiddleware.js | 6 +- packages/react-dev-utils/package.json | 2 + .../redirectServedPathMiddleware.js | 26 ++++ packages/react-scripts/config/paths.js | 38 ++---- .../react-scripts/config/webpack.config.js | 39 ++---- .../config/webpackDevServer.config.js | 28 ++-- packages/react-scripts/package.json | 2 +- packages/react-scripts/scripts/build.js | 2 +- packages/react-scripts/scripts/start.js | 8 +- 14 files changed, 290 insertions(+), 75 deletions(-) create mode 100644 packages/react-dev-utils/__tests__/getPublicUrlOrPath.test.js create mode 100644 packages/react-dev-utils/getPublicUrlOrPath.js create mode 100644 packages/react-dev-utils/redirectServedPathMiddleware.js diff --git a/docusaurus/docs/advanced-configuration.md b/docusaurus/docs/advanced-configuration.md index ab7f6ca8e2e..bf7777a413b 100644 --- a/docusaurus/docs/advanced-configuration.md +++ b/docusaurus/docs/advanced-configuration.md @@ -17,7 +17,7 @@ You can adjust various development and production settings by setting environmen | WDS_SOCKET_HOST | βœ… Used | 🚫 Ignored | When set, Create React App will run the development server with a custom websocket hostname for hot module reloading. Normally, `webpack-dev-server` defaults to `window.location.hostname` for the SockJS hostname. You may use this variable to start local development on more than one Create React App project at a time. See [webpack-dev-server documentation](https://webpack.js.org/configuration/dev-server/#devserversockhost) for more details. | | WDS_SOCKET_PATH | βœ… Used | 🚫 Ignored | When set, Create React App will run the development server with a custom websocket path for hot module reloading. Normally, `webpack-dev-server` defaults to `/sockjs-node` for the SockJS pathname. You may use this variable to start local development on more than one Create React App project at a time. See [webpack-dev-server documentation](https://webpack.js.org/configuration/dev-server/#devserversockpath) for more details. | | WDS_SOCKET_PORT | βœ… Used | 🚫 Ignored | When set, Create React App will run the development server with a custom websocket port for hot module reloading. Normally, `webpack-dev-server` defaults to `window.location.port` for the SockJS port. You may use this variable to start local development on more than one Create React App project at a time. See [webpack-dev-server documentation](https://webpack.js.org/configuration/dev-server/#devserversockport) for more details. | -| PUBLIC_URL | 🚫 Ignored | βœ… Used | Create React App assumes your application is hosted at the serving web server's root or a subpath as specified in [`package.json` (`homepage`)](deployment#building-for-relative-paths). Normally, Create React App ignores the hostname. You may use this variable to force assets to be referenced verbatim to the url you provide (hostname included). This may be particularly useful when using a CDN to host your application. | +| PUBLIC_URL | βœ… Used | βœ… Used | Create React App assumes your application is hosted at the serving web server's root or a subpath as specified in [`package.json` (`homepage`)](deployment#building-for-relative-paths). Normally, Create React App ignores the hostname. You may use this variable to force assets to be referenced verbatim to the url you provide (hostname included). This may be particularly useful when using a CDN to host your application. | | CI | βœ… Used | βœ… Used | When set to `true`, Create React App treats warnings as failures in the build. It also makes the test runner non-watching. Most CIs set this flag by default. | | REACT_EDITOR | βœ… Used | 🚫 Ignored | When an app crashes in development, you will see an error overlay with clickable stack trace. When you click on it, Create React App will try to determine the editor you are using based on currently running processes, and open the relevant source file. You can [send a pull request to detect your editor of choice](https://github.com/facebook/create-react-app/issues/2636). Setting this environment variable overrides the automatic detection. If you do it, make sure your systems [PATH]() environment variable points to your editor’s bin folder. You can also set it to `none` to disable it completely. | | CHOKIDAR_USEPOLLING | βœ… Used | 🚫 Ignored | When set to `true`, the watcher runs in polling mode, as necessary inside a VM. Use this option if `npm start` isn't detecting changes. | diff --git a/packages/react-dev-utils/README.md b/packages/react-dev-utils/README.md index 760b4cca52d..5f64db3bde4 100644 --- a/packages/react-dev-utils/README.md +++ b/packages/react-dev-utils/README.md @@ -287,9 +287,14 @@ getProcessForPort(3000); On macOS, tries to find a known running editor process and opens the file in it. It can also be explicitly configured by `REACT_EDITOR`, `VISUAL`, or `EDITOR` environment variables. For example, you can put `REACT_EDITOR=atom` in your `.env.local` file, and Create React App will respect that. -#### `noopServiceWorkerMiddleware(): ExpressMiddleware` +#### `noopServiceWorkerMiddleware(servedPath: string): ExpressMiddleware` -Returns Express middleware that serves a `/service-worker.js` that resets any previously set service worker configuration. Useful for development. +Returns Express middleware that serves a `${servedPath}/service-worker.js` that resets any previously set service worker configuration. Useful for development. + +#### `redirectServedPathMiddleware(servedPath: string): ExpressMiddleware` + +Returns Express middleware that redirects to `${servedPath}/${req.path}`, if `req.url` +does not start with `servedPath`. Useful for development. #### `openBrowser(url: string): boolean` @@ -314,7 +319,7 @@ Pass your parsed `package.json` object as `appPackage`, your the URL where you p ```js const appPackage = require(paths.appPackageJson); -const publicUrl = paths.publicUrl; +const publicUrl = paths.publicUrlOrPath; const publicPath = config.output.publicPath; printHostingInstructions(appPackage, publicUrl, publicPath, 'build', true); ``` @@ -344,7 +349,7 @@ The `args` object accepts a number of properties: Creates a WebpackDevServer `proxy` configuration object from the `proxy` setting in `package.json`. -##### `prepareUrls(protocol: string, host: string, port: number): Object` +##### `prepareUrls(protocol: string, host: string, port: number, pathname: string = '/'): Object` Returns an object with local and remote URLs for the development server. Pass this object to `createCompiler()` described above. diff --git a/packages/react-dev-utils/WebpackDevServerUtils.js b/packages/react-dev-utils/WebpackDevServerUtils.js index a4d45cc30d1..26b36fca395 100644 --- a/packages/react-dev-utils/WebpackDevServerUtils.js +++ b/packages/react-dev-utils/WebpackDevServerUtils.js @@ -22,20 +22,20 @@ const forkTsCheckerWebpackPlugin = require('./ForkTsCheckerWebpackPlugin'); const isInteractive = process.stdout.isTTY; -function prepareUrls(protocol, host, port) { +function prepareUrls(protocol, host, port, pathname = '/') { const formatUrl = hostname => url.format({ protocol, hostname, port, - pathname: '/', + pathname, }); const prettyPrintUrl = hostname => url.format({ protocol, hostname, port: chalk.bold(port), - pathname: '/', + pathname, }); const isUnspecifiedHost = host === '0.0.0.0' || host === '::'; diff --git a/packages/react-dev-utils/__tests__/getPublicUrlOrPath.test.js b/packages/react-dev-utils/__tests__/getPublicUrlOrPath.test.js new file mode 100644 index 00000000000..9e9677edc9f --- /dev/null +++ b/packages/react-dev-utils/__tests__/getPublicUrlOrPath.test.js @@ -0,0 +1,128 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +'use strict'; + +const getPublicUrlOrPath = require('../getPublicUrlOrPath'); + +const tests = [ + // DEVELOPMENT with homepage + { dev: true, homepage: '/', expect: '/' }, + { dev: true, homepage: '/test', expect: '/test/' }, + { dev: true, homepage: '/test/', expect: '/test/' }, + { dev: true, homepage: './', expect: '/' }, + { dev: true, homepage: '../', expect: '/' }, + { dev: true, homepage: '../test', expect: '/' }, + { dev: true, homepage: './test/path', expect: '/' }, + { dev: true, homepage: 'https://create-react-app.dev/', expect: '/' }, + { + dev: true, + homepage: 'https://create-react-app.dev/test', + expect: '/test/', + }, + // DEVELOPMENT with publicURL + { dev: true, publicUrl: '/', expect: '/' }, + { dev: true, publicUrl: '/test', expect: '/test/' }, + { dev: true, publicUrl: '/test/', expect: '/test/' }, + { dev: true, publicUrl: './', expect: '/' }, + { dev: true, publicUrl: '../', expect: '/' }, + { dev: true, publicUrl: '../test', expect: '/' }, + { dev: true, publicUrl: './test/path', expect: '/' }, + { dev: true, publicUrl: 'https://create-react-app.dev/', expect: '/' }, + { + dev: true, + publicUrl: 'https://create-react-app.dev/test', + expect: '/test/', + }, + // DEVELOPMENT with publicURL and homepage + { dev: true, publicUrl: '/', homepage: '/test', expect: '/' }, + { dev: true, publicUrl: '/test', homepage: '/path', expect: '/test/' }, + { dev: true, publicUrl: '/test/', homepage: '/test/path', expect: '/test/' }, + { dev: true, publicUrl: './', homepage: '/test', expect: '/' }, + { dev: true, publicUrl: '../', homepage: '/test', expect: '/' }, + { dev: true, publicUrl: '../test', homepage: '/test', expect: '/' }, + { dev: true, publicUrl: './test/path', homepage: '/test', expect: '/' }, + { + dev: true, + publicUrl: 'https://create-react-app.dev/', + homepage: '/test', + expect: '/', + }, + { + dev: true, + publicUrl: 'https://create-react-app.dev/test', + homepage: '/path', + expect: '/test/', + }, + + // PRODUCTION with homepage + { dev: false, homepage: '/', expect: '/' }, + { dev: false, homepage: '/test', expect: '/test/' }, + { dev: false, homepage: '/test/', expect: '/test/' }, + { dev: false, homepage: './', expect: './' }, + { dev: false, homepage: '../', expect: '../' }, + { dev: false, homepage: '../test', expect: '../test/' }, + { dev: false, homepage: './test/path', expect: './test/path/' }, + { dev: false, homepage: 'https://create-react-app.dev/', expect: '/' }, + { + dev: false, + homepage: 'https://create-react-app.dev/test', + expect: '/test/', + }, + // PRODUCTION with publicUrl + { dev: false, publicUrl: '/', expect: '/' }, + { dev: false, publicUrl: '/test', expect: '/test/' }, + { dev: false, publicUrl: '/test/', expect: '/test/' }, + { dev: false, publicUrl: './', expect: './' }, + { dev: false, publicUrl: '../', expect: '../' }, + { dev: false, publicUrl: '../test', expect: '../test/' }, + { dev: false, publicUrl: './test/path', expect: './test/path/' }, + { + dev: false, + publicUrl: 'https://create-react-app.dev/', + expect: 'https://create-react-app.dev/', + }, + { + dev: false, + publicUrl: 'https://create-react-app.dev/test', + expect: 'https://create-react-app.dev/test/', + }, + // PRODUCTION with publicUrl and homepage + { dev: false, publicUrl: '/', homepage: '/test', expect: '/' }, + { dev: false, publicUrl: '/test', homepage: '/path', expect: '/test/' }, + { dev: false, publicUrl: '/test/', homepage: '/test/path', expect: '/test/' }, + { dev: false, publicUrl: './', homepage: '/test', expect: './' }, + { dev: false, publicUrl: '../', homepage: '/test', expect: '../' }, + { dev: false, publicUrl: '../test', homepage: '/test', expect: '../test/' }, + { + dev: false, + publicUrl: './test/path', + homepage: '/test', + expect: './test/path/', + }, + { + dev: false, + publicUrl: 'https://create-react-app.dev/', + homepage: '/test', + expect: 'https://create-react-app.dev/', + }, + { + dev: false, + publicUrl: 'https://create-react-app.dev/test', + homepage: '/path', + expect: 'https://create-react-app.dev/test/', + }, +]; + +describe('getPublicUrlOrPath', () => { + tests.forEach(t => + it(JSON.stringify(t), () => { + const actual = getPublicUrlOrPath(t.dev, t.homepage, t.publicUrl); + expect(actual).toBe(t.expect); + }) + ); +}); diff --git a/packages/react-dev-utils/getPublicUrlOrPath.js b/packages/react-dev-utils/getPublicUrlOrPath.js new file mode 100644 index 00000000000..dbb7cda5aa2 --- /dev/null +++ b/packages/react-dev-utils/getPublicUrlOrPath.js @@ -0,0 +1,65 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +'use strict'; + +const { URL } = require('url'); + +module.exports = getPublicUrlOrPath; + +/** + * Returns a URL or a path with slash at the end + * In production can be URL, abolute path, relative path + * In development always will be an absolute path + * In development can use `path` module functions for operations + * + * @param {boolean} isEnvDevelopment + * @param {(string|undefined)} homepage a valid url or pathname + * @param {(string|undefined)} envPublicUrl a valid url or pathname + * @returns {string} + */ +function getPublicUrlOrPath(isEnvDevelopment, homepage, envPublicUrl) { + const stubDomain = 'https://create-react-app.dev'; + + if (envPublicUrl) { + // ensure last slash exists + envPublicUrl = envPublicUrl.endsWith('/') + ? envPublicUrl + : envPublicUrl + '/'; + + // validate if `envPublicUrl` is a URL or path like + // `stubDomain` is ignored if `envPublicUrl` contains a domain + const validPublicUrl = new URL(envPublicUrl, stubDomain); + + return isEnvDevelopment + ? envPublicUrl.startsWith('.') + ? '/' + : validPublicUrl.pathname + : // Some apps do not use client-side routing with pushState. + // For these, "homepage" can be set to "." to enable relative asset paths. + envPublicUrl; + } + + if (homepage) { + // strip last slash if exists + homepage = homepage.endsWith('/') ? homepage : homepage + '/'; + + // validate if `homepage` is a URL or path like and use just pathname + const validHomepagePathname = new URL(homepage, stubDomain).pathname; + return isEnvDevelopment + ? homepage.startsWith('.') + ? '/' + : validHomepagePathname + : // Some apps do not use client-side routing with pushState. + // For these, "homepage" can be set to "." to enable relative asset paths. + homepage.startsWith('.') + ? homepage + : validHomepagePathname; + } + + return '/'; +} diff --git a/packages/react-dev-utils/noopServiceWorkerMiddleware.js b/packages/react-dev-utils/noopServiceWorkerMiddleware.js index 568ff4d6519..4e660b57643 100644 --- a/packages/react-dev-utils/noopServiceWorkerMiddleware.js +++ b/packages/react-dev-utils/noopServiceWorkerMiddleware.js @@ -7,9 +7,11 @@ 'use strict'; -module.exports = function createNoopServiceWorkerMiddleware() { +const path = require('path'); + +module.exports = function createNoopServiceWorkerMiddleware(servedPath) { return function noopServiceWorkerMiddleware(req, res, next) { - if (req.url === '/service-worker.js') { + if (req.url === path.join(servedPath, 'service-worker.js')) { res.setHeader('Content-Type', 'text/javascript'); res.send( `// This service worker file is effectively a 'no-op' that will reset any diff --git a/packages/react-dev-utils/package.json b/packages/react-dev-utils/package.json index e9a48c96803..e2de53d4b8f 100644 --- a/packages/react-dev-utils/package.json +++ b/packages/react-dev-utils/package.json @@ -29,6 +29,7 @@ "getCacheIdentifier.js", "getCSSModuleLocalIdent.js", "getProcessForPort.js", + "getPublicUrlOrPath.js", "globby.js", "ignoredFiles.js", "immer.js", @@ -44,6 +45,7 @@ "openChrome.applescript", "printBuildError.js", "printHostingInstructions.js", + "redirectServedPathMiddleware.js", "typescriptFormatter.js", "WatchMissingNodeModulesPlugin.js", "WebpackDevServerUtils.js", diff --git a/packages/react-dev-utils/redirectServedPathMiddleware.js b/packages/react-dev-utils/redirectServedPathMiddleware.js new file mode 100644 index 00000000000..a71578f0a9f --- /dev/null +++ b/packages/react-dev-utils/redirectServedPathMiddleware.js @@ -0,0 +1,26 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +'use strict'; + +const path = require('path'); + +module.exports = function createRedirectServedPathMiddleware(servedPath) { + // remove end slash so user can land on `/test` instead of `/test/` + servedPath = servedPath.slice(0, -1); + return function redirectServedPathMiddleware(req, res, next) { + if ( + servedPath === '' || + req.url === servedPath || + req.url.startsWith(servedPath) + ) { + next(); + } else { + const newPath = path.join(servedPath, req.path !== '/' ? req.path : ''); + res.redirect(newPath); + } + }; +}; diff --git a/packages/react-scripts/config/paths.js b/packages/react-scripts/config/paths.js index acaca7f4d48..f842a39a24b 100644 --- a/packages/react-scripts/config/paths.js +++ b/packages/react-scripts/config/paths.js @@ -10,41 +10,24 @@ const path = require('path'); const fs = require('fs'); -const url = require('url'); +const getPublicUrlOrPath = require('react-dev-utils/getPublicUrlOrPath'); // Make sure any symlinks in the project folder are resolved: // https://github.com/facebook/create-react-app/issues/637 const appDirectory = fs.realpathSync(process.cwd()); const resolveApp = relativePath => path.resolve(appDirectory, relativePath); -const envPublicUrl = process.env.PUBLIC_URL; - -function ensureSlash(inputPath, needsSlash) { - const hasSlash = inputPath.endsWith('/'); - if (hasSlash && !needsSlash) { - return inputPath.substr(0, inputPath.length - 1); - } else if (!hasSlash && needsSlash) { - return `${inputPath}/`; - } else { - return inputPath; - } -} - -const getPublicUrl = appPackageJson => - envPublicUrl || require(appPackageJson).homepage; - // We use `PUBLIC_URL` environment variable or "homepage" field to infer // "public path" at which the app is served. // Webpack needs to know it to put the right