Skip to content

Commit 9ef53fd

Browse files
author
Ron Meldiner
committed
add webpack-env-define-plugin
1 parent 79160b8 commit 9ef53fd

File tree

7 files changed

+155
-55
lines changed

7 files changed

+155
-55
lines changed

packages/react-scripts/config/env.js

-39
This file was deleted.

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

+18-5
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ var HtmlWebpackPlugin = require('html-webpack-plugin');
1616
var CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');
1717
var InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
1818
var WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin');
19-
var getClientEnvironment = require('./env');
19+
var EnvDefinePlugin = require('webpack-env-define-plugin');
2020
var paths = require('./paths');
2121

2222
// Webpack uses `publicPath` to determine where the app is being served from.
@@ -26,8 +26,6 @@ var publicPath = '/';
2626
// as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
2727
// Omit trailing slash as %PUBLIC_PATH%/xyz looks better than %PUBLIC_PATH%xyz.
2828
var publicUrl = '';
29-
// Get environment variables to inject into our app.
30-
var env = getClientEnvironment(publicUrl);
3129

3230
// This is the development configuration.
3331
// It is focused on developer experience and fast rebuilds.
@@ -196,8 +194,23 @@ module.exports = {
196194
template: paths.appHtml,
197195
}),
198196
// Makes some environment variables available to the JS code, for example:
199-
// if (process.env.NODE_ENV === 'development') { ... }. See `./env.js`.
200-
new webpack.DefinePlugin(env),
197+
// if (process.env.NODE_ENV === 'development') { ... }.
198+
new EnvDefinePlugin({
199+
// Grab REACT_APP_* environment variables
200+
regex: /^REACT_APP_/i,
201+
customVariables: {
202+
// Useful for determining whether we’re running in production mode.
203+
// Most importantly, it switches React into the correct mode.
204+
'NODE_ENV': JSON.stringify(
205+
process.env.NODE_ENV || 'development'
206+
),
207+
// Useful for resolving the correct path to static assets in `public`.
208+
// For example, <img src={process.env.PUBLIC_URL + '/img/logo.png'} />.
209+
// This should only be used as an escape hatch. Normally you would put
210+
// images into the `src` and `import` them in code to get their paths.
211+
'PUBLIC_URL': JSON.stringify(publicUrl)
212+
}
213+
}),
201214
// This is necessary to emit hot updates (currently CSS only):
202215
new webpack.HotModuleReplacementPlugin(),
203216
// Watcher doesn't work well if you mistype casing in a path so we use

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

+18-11
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ var ManifestPlugin = require('webpack-manifest-plugin');
1818
var InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
1919
var url = require('url');
2020
var paths = require('./paths');
21-
var getClientEnvironment = require('./env');
21+
var EnvDefinePlugin = require('webpack-env-define-plugin');
2222

2323
function ensureSlash(path, needsSlash) {
2424
var hasSlash = path.endsWith('/');
@@ -45,14 +45,6 @@ var publicPath = ensureSlash(homepagePathname, true);
4545
// as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
4646
// Omit trailing slash as %PUBLIC_PATH%/xyz looks better than %PUBLIC_PATH%xyz.
4747
var publicUrl = ensureSlash(homepagePathname, false);
48-
// Get environment variables to inject into our app.
49-
var env = getClientEnvironment(publicUrl);
50-
51-
// Assert this just to be safe.
52-
// Development builds of React are slow and not intended for production.
53-
if (env['process.env'].NODE_ENV !== '"production"') {
54-
throw new Error('Production builds must have NODE_ENV=production.');
55-
}
5648

5749
// This is the production configuration.
5850
// It compiles slowly and is focused on producing a fast and minimal bundle.
@@ -228,10 +220,25 @@ module.exports = {
228220
}
229221
}),
230222
// Makes some environment variables available to the JS code, for example:
231-
// if (process.env.NODE_ENV === 'production') { ... }. See `./env.js`.
223+
// if (process.env.NODE_ENV === 'production') { ... }.
232224
// It is absolutely essential that NODE_ENV was set to production here.
233225
// Otherwise React will be compiled in the very slow development mode.
234-
new webpack.DefinePlugin(env),
226+
new EnvDefinePlugin({
227+
// Grab REACT_APP_* environment variables
228+
regex: /^REACT_APP_/i,
229+
customVariables: {
230+
// Useful for determining whether we’re running in production mode.
231+
// Most importantly, it switches React into the correct mode.
232+
'NODE_ENV': JSON.stringify(
233+
process.env.NODE_ENV || 'production'
234+
),
235+
// Useful for resolving the correct path to static assets in `public`.
236+
// For example, <img src={process.env.PUBLIC_URL + '/img/logo.png'} />.
237+
// This should only be used as an escape hatch. Normally you would put
238+
// images into the `src` and `import` them in code to get their paths.
239+
'PUBLIC_URL': JSON.stringify(publicUrl)
240+
}
241+
}),
235242
// This helps ensure the builds are consistent if source hasn't changed:
236243
new webpack.optimize.OccurrenceOrderPlugin(),
237244
// Try to dedupe duplicated modules, if any:

packages/react-scripts/package.json

+1
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,7 @@
6464
"url-loader": "0.5.7",
6565
"webpack": "1.13.2",
6666
"webpack-dev-server": "1.16.2",
67+
"webpack-env-define-plugin": "1.0.0",
6768
"webpack-manifest-plugin": "1.1.0",
6869
"whatwg-fetch": "1.0.0"
6970
},
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
# webpack-env-define-plugin
2+
3+
This package includes a webpack plugin used by [Create React App](https://github.com/facebookincubator/create-react-app).
4+
The plugin grabs environment variables that follows a specified regex and injects them into the application using the
5+
webpack DefinePlugin.
6+
In addition, the plugin allows defining custom environment variables to be injected.
7+
8+
## Usage in Create React App Projects
9+
10+
See [webpack.config.dev.js](https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/config/webpack.config.dev.js#L200) and [webpack.config.prod.js](https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/config/webpack.config.prod.js#L234).
11+
12+
## Usage Outside of Create React App
13+
14+
If you want to use this webpack plugin in a project not built with Create React App, you can install it with following steps.
15+
16+
First, install this package.
17+
18+
```
19+
npm install --save-dev webpack-env-define-plugin
20+
```
21+
22+
Then reference it in your webpack config:
23+
24+
```js
25+
var EnvDefinePlugin = require('../../webpack-env-define-plugin');
26+
```
27+
28+
and define it as a plugin in the webpack config plugin section:
29+
30+
```js
31+
plugins: [
32+
...
33+
new EnvDefinePlugin({
34+
// Grab MY_PREFIX_* environment variables
35+
regex: /^MY_PREFIX_/i,
36+
customVariables: {
37+
// Useful for determining whether we’re running in production mode.
38+
// Most importantly, it switches React into the correct mode.
39+
'MY_ENV_VAR': JSON.stringify(
40+
process.env.MY_ENV_VAR || 'default'
41+
)
42+
}
43+
}),
44+
...
45+
]
46+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/**
2+
* Copyright (c) 2015-present, Facebook, Inc.
3+
* All rights reserved.
4+
*
5+
* This source code is licensed under the BSD-style license found in the
6+
* LICENSE file in the root directory of this source tree. An additional grant
7+
* of patent rights can be found in the PATENTS file in the same directory.
8+
*/
9+
'use strict';
10+
11+
const DefinePlugin = require('webpack').DefinePlugin;
12+
13+
/**
14+
* Webpack plugin to inject environment variables that pass a regex test. The plugin also support
15+
* custom variables by passing them in the options argument
16+
*
17+
* @param {Object} options - The plugin configuration
18+
* @param {string} options.regex - The regex to select the environment variables by
19+
* @param {Object.<string, string>} options.customVariables - A map that its keys are the
20+
* custom injected environment
21+
* variable names and its values are the variable values
22+
* @constructor - Returns a new EnvDefinePlugin instance
23+
*/
24+
function EnvDefinePlugin(options) {
25+
this.regex = options.regex || /.*/;
26+
this.customVariables = options.customVariables || {};
27+
}
28+
29+
/**
30+
* Grabs environment variables that meets the regex test and prepare them to be injected into the
31+
* application via DefinePlugin in Webpack configuration.
32+
* @param {string} regex - The regex to select the environment variables by
33+
* @param {Object.<string, string>} customVariables - A map where its keys are the custom injected environment
34+
* @returns {{[process.env]: *}} - A DefinePlugin configuration
35+
*/
36+
function getClientEnvironment(regex, customVariables) {
37+
const processEnv = Object
38+
.keys(process.env)
39+
.filter(key => regex.test(key))
40+
.reduce((env, key) => {
41+
env[key] = JSON.stringify(process.env[key]);
42+
return env;
43+
}, customVariables);
44+
return { 'process.env': processEnv };
45+
}
46+
47+
EnvDefinePlugin.prototype.apply = function(compiler) {
48+
compiler.apply(new DefinePlugin(getClientEnvironment(this.regex, this.customVariables)));
49+
};
50+
51+
module.exports = EnvDefinePlugin;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
{
2+
"name": "webpack-env-define-plugin",
3+
"version": "1.0.0",
4+
"description": "Webpack plugin to inject environment variables that meet a specificed pattern",
5+
"main": "index.js",
6+
"repository": "facebookincubator/create-react-app",
7+
"license": "BSD-3-Clause",
8+
"bugs": {
9+
"url": "https://github.com/facebookincubator/create-react-app/issues"
10+
},
11+
"dependencies": {
12+
"webpack": "^1.13.3"
13+
},
14+
"contributors": [
15+
{
16+
"name": "Ron Meldiner",
17+
"email": "[email protected]",
18+
"url": "https://github.com/meldiner"
19+
}
20+
]
21+
}

0 commit comments

Comments
 (0)