Skip to content

Commit

Permalink
feat(react-scripts): allow PUBLIC_URL in develoment mode (#7259)
Browse files Browse the repository at this point in the history
Co-authored-by: Eric Clemmons <[email protected]>
Co-authored-by: Alex Guerra <[email protected]>
Co-authored-by: Kelly <[email protected]>

Co-authored-by: Eric Clemmons <[email protected]>
Co-authored-by: Alex Guerra <[email protected]>
Co-authored-by: Kelly <[email protected]>
  • Loading branch information
4 people authored Feb 2, 2020
1 parent 3190e4f commit 1cbc6f7
Show file tree
Hide file tree
Showing 14 changed files with 290 additions and 75 deletions.
2 changes: 1 addition & 1 deletion docusaurus/docs/advanced-configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -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](<https://en.wikipedia.org/wiki/PATH_(variable)>) 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. |
Expand Down
13 changes: 9 additions & 4 deletions packages/react-dev-utils/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`

Expand All @@ -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);
```
Expand Down Expand Up @@ -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.

Expand Down
6 changes: 3 additions & 3 deletions packages/react-dev-utils/WebpackDevServerUtils.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 === '::';
Expand Down
128 changes: 128 additions & 0 deletions packages/react-dev-utils/__tests__/getPublicUrlOrPath.test.js
Original file line number Diff line number Diff line change
@@ -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);
})
);
});
65 changes: 65 additions & 0 deletions packages/react-dev-utils/getPublicUrlOrPath.js
Original file line number Diff line number Diff line change
@@ -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 '/';
}
6 changes: 4 additions & 2 deletions packages/react-dev-utils/noopServiceWorkerMiddleware.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,11 @@

'use strict';

module.exports = function createNoopServiceWorkerMiddleware() {
const path = require('path');

module.exports = function createNoopServiceWorkerMiddleware(servedPath) {

This comment has been minimized.

Copy link
@confirmTing

confirmTing Feb 25, 2020

the paramter for path can't be 'undefined'

return function noopServiceWorkerMiddleware(req, res, next) {
if (req.url === '/service-worker.js') {
if (req.url === path.join(servedPath, 'service-worker.js')) {

This comment has been minimized.

Copy link
@anton-bot

anton-bot Feb 26, 2020

this line causes bug #8499 in version react-dev-utils 10.2. Downgrading to 10.1 helps.

res.setHeader('Content-Type', 'text/javascript');
res.send(
`// This service worker file is effectively a 'no-op' that will reset any
Expand Down
2 changes: 2 additions & 0 deletions packages/react-dev-utils/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
"getCacheIdentifier.js",
"getCSSModuleLocalIdent.js",
"getProcessForPort.js",
"getPublicUrlOrPath.js",
"globby.js",
"ignoredFiles.js",
"immer.js",
Expand All @@ -44,6 +45,7 @@
"openChrome.applescript",
"printBuildError.js",
"printHostingInstructions.js",
"redirectServedPathMiddleware.js",
"typescriptFormatter.js",
"WatchMissingNodeModulesPlugin.js",
"WebpackDevServerUtils.js",
Expand Down
26 changes: 26 additions & 0 deletions packages/react-dev-utils/redirectServedPathMiddleware.js
Original file line number Diff line number Diff line change
@@ -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);
}
};
};
38 changes: 9 additions & 29 deletions packages/react-scripts/config/paths.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 <script> hrefs into HTML even in
// single-page apps that may serve index.html for nested URLs like /todos/42.
// We can't use a relative path in HTML because we don't want to load something
// like /todos/42/static/js/bundle.7289d.js. We have to know the root.
function getServedPath(appPackageJson) {
const publicUrl = getPublicUrl(appPackageJson);
const servedUrl =
envPublicUrl || (publicUrl ? url.parse(publicUrl).pathname : '/');
return ensureSlash(servedUrl, true);
}
const publicUrlOrPath = getPublicUrlOrPath(
process.env.NODE_ENV === 'development',
require(resolveApp('package.json')).homepage,
process.env.PUBLIC_URL
);

const moduleFileExtensions = [
'web.mjs',
Expand Down Expand Up @@ -89,8 +72,7 @@ module.exports = {
testsSetup: resolveModule(resolveApp, 'src/setupTests'),
proxySetup: resolveApp('src/setupProxy.js'),
appNodeModules: resolveApp('node_modules'),
publicUrl: getPublicUrl(resolveApp('package.json')),
servedPath: getServedPath(resolveApp('package.json')),
publicUrlOrPath,
};

// @remove-on-eject-begin
Expand All @@ -112,8 +94,7 @@ module.exports = {
testsSetup: resolveModule(resolveApp, 'src/setupTests'),
proxySetup: resolveApp('src/setupProxy.js'),
appNodeModules: resolveApp('node_modules'),
publicUrl: getPublicUrl(resolveApp('package.json')),
servedPath: getServedPath(resolveApp('package.json')),
publicUrlOrPath,
// These properties only exist before ejecting:
ownPath: resolveOwn('.'),
ownNodeModules: resolveOwn('node_modules'), // This is empty on npm 3
Expand Down Expand Up @@ -148,8 +129,7 @@ if (
testsSetup: resolveModule(resolveOwn, `${templatePath}/src/setupTests`),
proxySetup: resolveOwn(`${templatePath}/src/setupProxy.js`),
appNodeModules: resolveOwn('node_modules'),
publicUrl: getPublicUrl(resolveOwn('package.json')),
servedPath: getServedPath(resolveOwn('package.json')),
publicUrlOrPath,
// These properties only exist before ejecting:
ownPath: resolveOwn('.'),
ownNodeModules: resolveOwn('node_modules'),
Expand Down
Loading

0 comments on commit 1cbc6f7

Please sign in to comment.