Custom environment variables: unset variables cause unexpected minification
See original GitHub issueCan you reproduce the problem with latest npm?
yes (with latest yarn)
Description
If a custom environment variable is not set minification will not strip out dead code related to it.
This could cause unwanted development assets to go into the production build if the environment variables are not properly set.
If this is works as planned perhaps I could try to create a PR to mention this in the documentation.
Please consider the following example when running yarn run build
:
if (process.env.REACT_APP_FOO === 'bar') {
console.log('REACT_APP_FOO: bar')
} else {
console.log('REACT_APP_FOO: something else');
}
Expected behavior
string REACT_APP_FOO: bar
is not included in the bundle.
Actual behavior
REACT_APP_FOO: bar
is included in the bundle.
Environment
-
npm ls react-scripts
(if you haven’t ejected): └── react-scripts@0.9.4 -
node -v
: v6.10.0 -
npm -v
: 3.10.10 -
Operating system: macOS
-
Browser and version: Chrome 56.0.2924.87 (64-bit)
Reproducible Demo
Repo: https://github.com/mfonsen/create-react-app-undefined-env-vars Steps:
cd my-app
yarn
yarn run build
cat build/static/js/main.*.js | grep -Eo "REACT_APP_FOO: bar"
# returns REACT_APP_FOO: bar
REACT_APP_FOO="foobar" yarn run build
# does not return anything
Issue Analytics
- State:
- Created 7 years ago
- Comments:7 (4 by maintainers)
I think this is the expected behavior.
For differentiating between production and development builds, I recommend checking
process.env.NODE_ENV
which is hardcoded and will always be specified.For custom environment variables, you can employ a trick like:
Then at least you’d get a completely crashing bundle and presumably would find the mistake soon enough.
But technically accessing
process.env.WHATEVER
should be safe so IMO we shouldn’t introduce non-obvious semantics there (like suddenly failing if it is missing).I’ve just noticed this same issue. If you reference an unset env var like this:
Then the output of the build from CRA is:
I have tested with just webpack (i.e. no CRA), and it outputs (as expected) this:
When encountering an unknown env var, webpack will leave the code verbatim, but define
process.env = {}
somewhere else, so the code evaluates toundefined
.I’m not sure what is causing this in CRA, but it should be fixed. It’s wasteful to output the whole
process.env
object just to get something that evaluates toundefined
, you lose some dead code elimination as originally stated here, and it is also leaking some information in the bundle (though env var names are arguably insignificant, they could unwittingly reveal something you would not want exposed).@gaearon should i create a new issue for this? It’s the underlying cause of what was originally reported here