Skip to content

Commit 1ed362d

Browse files
Timerrandycoulman
authored andcommitted
Add PUBLIC_URL env variable for advanced use (facebook#937) (facebook#1504)
* Add `PUBLIC_URL` env variable for advanced use (facebook#937) * Add support for `PUBLIC_URL` env variable * Remove unnecessary duplications * Simplify served path choice logic * Honor PUBLIC_URL in development * Add e2e tests Enables serving static assets from specified host.
1 parent e05bf64 commit 1ed362d

File tree

11 files changed

+109
-47
lines changed

11 files changed

+109
-47
lines changed

packages/react-scripts/config/paths.js

+41-3
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111

1212
var path = require('path');
1313
var fs = require('fs');
14+
var url = require('url');
1415

1516
// ZEAL: Allow custom build paths via .env config.
1617
var buildPath = process.env.BUILD_PATH || 'build'
@@ -43,6 +44,37 @@ var nodePaths = (process.env.NODE_PATH || '')
4344
.filter(folder => !path.isAbsolute(folder))
4445
.map(resolveApp);
4546

47+
var envPublicUrl = process.env.PUBLIC_URL;
48+
49+
function ensureSlash(path, needsSlash) {
50+
var hasSlash = path.endsWith('/');
51+
if (hasSlash && !needsSlash) {
52+
return path.substr(path, path.length - 1);
53+
} else if (!hasSlash && needsSlash) {
54+
return path + '/';
55+
} else {
56+
return path;
57+
}
58+
}
59+
60+
function getPublicUrl(appPackageJson) {
61+
return envPublicUrl || require(appPackageJson).homepage;
62+
}
63+
64+
// We use `PUBLIC_URL` environment variable or "homepage" field to infer
65+
// "public path" at which the app is served.
66+
// Webpack needs to know it to put the right <script> hrefs into HTML even in
67+
// single-page apps that may serve index.html for nested URLs like /todos/42.
68+
// We can't use a relative path in HTML because we don't want to load something
69+
// like /todos/42/static/js/bundle.7289d.js. We have to know the root.
70+
function getServedPath(appPackageJson) {
71+
var publicUrl = getPublicUrl(appPackageJson);
72+
var servedUrl = envPublicUrl || (
73+
publicUrl ? url.parse(publicUrl).pathname : '/'
74+
);
75+
return ensureSlash(servedUrl, true);
76+
}
77+
4678
// config after eject: we're in ./config/
4779
module.exports = {
4880
appBuild: resolveApp(buildPath),
@@ -55,7 +87,9 @@ module.exports = {
5587
testsSetup: resolveApp('client/setupTests.js'),
5688
appNodeModules: resolveApp('node_modules'),
5789
ownNodeModules: resolveApp('node_modules'),
58-
nodePaths: nodePaths
90+
nodePaths: nodePaths,
91+
publicUrl: getPublicUrl(resolveApp('package.json')),
92+
servedPath: getServedPath(resolveApp('package.json'))
5993
};
6094

6195
// @remove-on-eject-begin
@@ -76,7 +110,9 @@ module.exports = {
76110
appNodeModules: resolveApp('node_modules'),
77111
// this is empty with npm3 but node resolution searches higher anyway:
78112
ownNodeModules: resolveOwn('../node_modules'),
79-
nodePaths: nodePaths
113+
nodePaths: nodePaths,
114+
publicUrl: getPublicUrl(resolveApp('package.json')),
115+
servedPath: getServedPath(resolveApp('package.json'))
80116
};
81117

82118
// config before publish: we're in ./packages/react-scripts/config/
@@ -92,7 +128,9 @@ if (__dirname.indexOf(path.join('packages', 'react-scripts', 'config')) !== -1)
92128
testsSetup: resolveOwn('../template/client/setupTests.js'),
93129
appNodeModules: resolveOwn('../node_modules'),
94130
ownNodeModules: resolveOwn('../node_modules'),
95-
nodePaths: nodePaths
131+
nodePaths: nodePaths,
132+
publicUrl: getPublicUrl(resolveOwn('../package.json')),
133+
servedPath: getServedPath(resolveOwn('../package.json'))
96134
};
97135
}
98136
// @remove-on-eject-end

packages/react-scripts/config/webpack.config.dev.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -129,7 +129,7 @@ module.exports = function(publicPath) {
129129
// ** ADDING/UPDATING LOADERS **
130130
// The "url" loader handles all assets unless explicitly excluded.
131131
// The `exclude` list *must* be updated with every change to loader extensions.
132-
// When adding a new loader, you must add its `test`
132+
// When adding a new loader, you must add its `test`
133133
// as a new entry in the `exclude` list for "url" loader.
134134

135135
// "url" loader embeds assets smaller than specified size as data URLs to avoid requests.

packages/react-scripts/config/webpack.config.prod.js

+4-22
Original file line numberDiff line numberDiff line change
@@ -24,31 +24,13 @@ var getClientEnvironment = require('./env');
2424
var path = require('path');
2525
// @remove-on-eject-end
2626

27-
function ensureSlash(path, needsSlash) {
28-
var hasSlash = path.endsWith('/');
29-
if (hasSlash && !needsSlash) {
30-
return path.substr(path, path.length - 1);
31-
} else if (!hasSlash && needsSlash) {
32-
return path + '/';
33-
} else {
34-
return path;
35-
}
36-
}
37-
38-
// We use "homepage" field to infer "public path" at which the app is served.
39-
// Webpack needs to know it to put the right <script> hrefs into HTML even in
40-
// single-page apps that may serve index.html for nested URLs like /todos/42.
41-
// We can't use a relative path in HTML because we don't want to load something
42-
// like /todos/42/static/js/bundle.7289d.js. We have to know the root.
43-
var homepagePath = require(paths.appPackageJson).homepage;
44-
var homepagePathname = homepagePath ? url.parse(homepagePath).pathname : '/';
4527
// Webpack uses `publicPath` to determine where the app is being served from.
4628
// It requires a trailing slash, or the file assets will get an incorrect path.
47-
var publicPath = ensureSlash(homepagePathname, true);
29+
var publicPath = paths.servedPath;
4830
// `publicUrl` is just like `publicPath`, but we will provide it to our app
4931
// as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
50-
// Omit trailing slash as %PUBLIC_PATH%/xyz looks better than %PUBLIC_PATH%xyz.
51-
var publicUrl = ensureSlash(homepagePathname, false);
32+
// Omit trailing slash as %PUBLIC_URL%/xyz looks better than %PUBLIC_URL%xyz.
33+
var publicUrl = publicPath.slice(0, -1);
5234
// Get environment variables to inject into our app.
5335
var env = getClientEnvironment(publicUrl);
5436

@@ -123,7 +105,7 @@ module.exports = {
123105
// ** ADDING/UPDATING LOADERS **
124106
// The "url" loader handles all assets unless explicitly excluded.
125107
// The `exclude` list *must* be updated with every change to loader extensions.
126-
// When adding a new loader, you must add its `test`
108+
// When adding a new loader, you must add its `test`
127109
// as a new entry in the `exclude` list in the "url" loader.
128110

129111
// "url" loader embeds assets smaller than specified size as data URLs to avoid requests.

packages/react-scripts/fixtures/kitchensink/integration/env.test.js

+15-6
Original file line numberDiff line numberDiff line change
@@ -3,22 +3,31 @@ import initDOM from './initDOM'
33

44
describe('Integration', () => {
55
describe('Environment variables', () => {
6+
it('file env variables', async () => {
7+
const doc = await initDOM('file-env-variables')
8+
9+
expect(doc.getElementById('feature-file-env-variables').textContent).to.equal('fromtheenvfile.')
10+
})
11+
612
it('NODE_PATH', async () => {
713
const doc = await initDOM('node-path')
814

915
expect(doc.getElementById('feature-node-path').childElementCount).to.equal(4)
1016
})
1117

12-
it('shell env variables', async () => {
13-
const doc = await initDOM('shell-env-variables')
18+
it('PUBLIC_URL', async () => {
19+
const doc = await initDOM('public-url')
1420

15-
expect(doc.getElementById('feature-shell-env-variables').textContent).to.equal('fromtheshell.')
21+
const prefix = process.env.NODE_ENV === 'development' ? '' : 'http://www.example.org/spa';
22+
expect(doc.getElementById('feature-public-url').textContent).to.equal(`${prefix}.`)
23+
expect(doc.querySelector('head link[rel="shortcut icon"]').getAttribute('href'))
24+
.to.equal(`${prefix}/favicon.ico`)
1625
})
1726

18-
it('file env variables', async () => {
19-
const doc = await initDOM('file-env-variables')
27+
it('shell env variables', async () => {
28+
const doc = await initDOM('shell-env-variables')
2029

21-
expect(doc.getElementById('feature-file-env-variables').textContent).to.equal('fromtheenvfile.')
30+
expect(doc.getElementById('feature-shell-env-variables').textContent).to.equal('fromtheshell.')
2231
})
2332
})
2433
})

packages/react-scripts/fixtures/kitchensink/integration/initDOM.js

+4-2
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,11 @@ if (process.env.E2E_FILE) {
1515
const markup = fs.readFileSync(file, 'utf8')
1616
getMarkup = () => markup
1717

18+
const pathPrefix = process.env.PUBLIC_URL.replace(/^https?:\/\/[^\/]+\/?/, '')
19+
1820
resourceLoader = (resource, callback) => callback(
1921
null,
20-
fs.readFileSync(path.join(path.dirname(file), resource.url.pathname), 'utf8')
22+
fs.readFileSync(path.join(path.dirname(file), resource.url.pathname.replace(pathPrefix, '')), 'utf8')
2123
)
2224
} else if (process.env.E2E_URL) {
2325
getMarkup = () => new Promise(resolve => {
@@ -37,7 +39,7 @@ if (process.env.E2E_FILE) {
3739

3840
export default feature => new Promise(async resolve => {
3941
const markup = await getMarkup()
40-
const host = process.env.E2E_URL || 'http://localhost:3000'
42+
const host = process.env.E2E_URL || 'http://www.example.org/spa:3000'
4143
const doc = jsdom.jsdom(markup, {
4244
features: {
4345
FetchExternalResources: ['script', 'css'],

packages/react-scripts/fixtures/kitchensink/src/App.js

+7-3
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ class BuiltEmitter extends Component {
66
}
77

88
componentDidMount() {
9-
const { feature } = this.props
9+
const { feature } = this.props;
1010

1111
// Class components must call this.props.onReady when they're ready for the test.
1212
// We will assume functional components are ready immediately after mounting.
@@ -44,7 +44,8 @@ class App extends Component {
4444
}
4545

4646
componentDidMount() {
47-
switch (location.hash.slice(1)) {
47+
const feature = location.hash.slice(1);
48+
switch (feature) {
4849
case 'array-destructuring':
4950
require.ensure([], () => this.setFeature(require('./features/syntax/ArrayDestructuring').default));
5051
break;
@@ -99,6 +100,9 @@ class App extends Component {
99100
case 'promises':
100101
require.ensure([], () => this.setFeature(require('./features/syntax/Promises').default));
101102
break;
103+
case 'public-url':
104+
require.ensure([], () => this.setFeature(require('./features/env/PublicUrl').default));
105+
break;
102106
case 'rest-and-default':
103107
require.ensure([], () => this.setFeature(require('./features/syntax/RestAndDefault').default));
104108
break;
@@ -117,7 +121,7 @@ class App extends Component {
117121
case 'unknown-ext-inclusion':
118122
require.ensure([], () => this.setFeature(require('./features/webpack/UnknownExtInclusion').default));
119123
break;
120-
default: throw new Error('Unknown feature!');
124+
default: throw new Error(`Missing feature "${feature}"`);
121125
}
122126
}
123127

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
import React from 'react'
2+
3+
export default () => (
4+
<span id="feature-public-url">{process.env.PUBLIC_URL}.</span>
5+
)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import React from 'react';
2+
import ReactDOM from 'react-dom';
3+
import PublicUrl from './PublicUrl';
4+
5+
describe('PUBLIC_URL', () => {
6+
it('renders without crashing', () => {
7+
const div = document.createElement('div');
8+
ReactDOM.render(<PublicUrl />, div);
9+
});
10+
});

packages/react-scripts/scripts/build.js

+9-7
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ require('dotenv').config({silent: true});
2121
var chalk = require('chalk');
2222
var fs = require('fs-extra');
2323
var path = require('path');
24+
var url = require('url');
2425
var filesize = require('filesize');
2526
var gzipSize = require('gzip-size').sync;
2627
var webpack = require('webpack');
@@ -158,15 +159,16 @@ function build(previousSizeMap) {
158159

159160
var openCommand = process.platform === 'win32' ? 'start' : 'open';
160161
var appPackage = require(paths.appPackageJson);
161-
var homepagePath = appPackage.homepage;
162+
var publicUrl = paths.publicUrl;
162163
var publicPath = config.output.publicPath;
163-
if (homepagePath && homepagePath.indexOf('.github.io/') !== -1) {
164+
var publicPathname = url.parse(publicPath).pathname;
165+
if (publicUrl && publicUrl.indexOf('.github.io/') !== -1) {
164166
// "homepage": "http://user.github.io/project"
165-
console.log('The project was built assuming it is hosted at ' + chalk.green(publicPath) + '.');
167+
console.log('The project was built assuming it is hosted at ' + chalk.green(publicPathname) + '.');
166168
console.log('You can control this with the ' + chalk.green('homepage') + ' field in your ' + chalk.cyan('package.json') + '.');
167169
console.log();
168170
console.log('The ' + chalk.cyan('build') + ' folder is ready to be deployed.');
169-
console.log('To publish it at ' + chalk.green(homepagePath) + ', run:');
171+
console.log('To publish it at ' + chalk.green(publicUrl) + ', run:');
170172
// If script deploy has been added to package.json, skip the instructions
171173
if (typeof appPackage.scripts.deploy === 'undefined') {
172174
console.log();
@@ -198,14 +200,14 @@ function build(previousSizeMap) {
198200
console.log('The ' + chalk.cyan('build') + ' folder is ready to be deployed.');
199201
console.log();
200202
} else {
201-
// no homepage or "homepage": "http://mywebsite.com"
202-
console.log('The project was built assuming it is hosted at the server root.');
203-
if (homepagePath) {
203+
if (publicUrl) {
204204
// "homepage": "http://mywebsite.com"
205+
console.log('The project was built assuming it is hosted at ' + chalk.green(publicUrl) + '.');
205206
console.log('You can control this with the ' + chalk.green('homepage') + ' field in your ' + chalk.cyan('package.json') + '.');
206207
console.log();
207208
} else {
208209
// no homepage
210+
console.log('The project was built assuming it is hosted at the server root.');
209211
console.log('To override this, specify the ' + chalk.green('homepage') + ' in your ' + chalk.cyan('package.json') + '.');
210212
console.log('For example, add this to build it for GitHub Pages:')
211213
console.log();

packages/react-scripts/scripts/start.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -243,7 +243,7 @@ function runDevServer(host, port, protocol) {
243243
// project directory is dangerous because we may expose sensitive files.
244244
// Instead, we establish a convention that only files in `public` directory
245245
// get served. Our build script will copy `public` into the `build` folder.
246-
// In `index.html`, you can get URL of `public` folder with %PUBLIC_PATH%:
246+
// In `index.html`, you can get URL of `public` folder with %PUBLIC_URL%:
247247
// <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
248248
// In JavaScript code, you can access it with `process.env.PUBLIC_URL`.
249249
// Note that we only recommend to use `public` folder as an escape hatch

tasks/e2e-kitchensink.sh

+12-2
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,11 @@ cd test-kitchensink
114114
npm link $root_path/packages/babel-preset-react-app
115115

116116
# Test the build
117-
NODE_PATH=src REACT_APP_SHELL_ENV_MESSAGE=fromtheshell npm run build
117+
REACT_APP_SHELL_ENV_MESSAGE=fromtheshell \
118+
NODE_PATH=src \
119+
PUBLIC_URL=http://www.example.org/spa/ \
120+
npm run build
121+
118122
# Check for expected output
119123
test -e build/*.html
120124
test -e build/static/js/main.*.js
@@ -144,6 +148,7 @@ E2E_FILE=./build/index.html \
144148
CI=true \
145149
NODE_PATH=src \
146150
NODE_ENV=production \
151+
PUBLIC_URL=http://www.example.org/spa/ \
147152
node_modules/.bin/mocha --require babel-register --require babel-polyfill integration/*.test.js
148153

149154
# ******************************************************************************
@@ -166,7 +171,11 @@ npm link $root_path/packages/react-scripts
166171
rm .babelrc
167172

168173
# Test the build
169-
NODE_PATH=src REACT_APP_SHELL_ENV_MESSAGE=fromtheshell npm run build
174+
REACT_APP_SHELL_ENV_MESSAGE=fromtheshell \
175+
NODE_PATH=src \
176+
PUBLIC_URL=http://www.example.org/spa/ \
177+
npm run build
178+
170179
# Check for expected output
171180
test -e build/*.html
172181
test -e build/static/js/main.*.js
@@ -196,6 +205,7 @@ E2E_FILE=./build/index.html \
196205
CI=true \
197206
NODE_ENV=production \
198207
NODE_PATH=src \
208+
PUBLIC_URL=http://www.example.org/spa/ \
199209
node_modules/.bin/mocha --require babel-register --require babel-polyfill integration/*.test.js
200210

201211
# Cleanup

0 commit comments

Comments
 (0)