create-react-app icon indicating copy to clipboard operation
create-react-app copied to clipboard

Environment variable evaluation not working in index.html

Open marco-gagliardi opened this issue 8 years ago • 6 comments

Is this a bug report?

yes

Did you try recovering your dependencies?

yes

Environment

System: OS: macOS High Sierra 10.13.6 CPU: x64 Intel(R) Core(TM) i5-7360U CPU @ 2.30GHz Binaries: Node: 10.9.0 - /usr/local/bin/node npm: 6.2.0 - /usr/local/bin/npm Browsers: Chrome: 70.0.3538.67 Safari: 12.0 npmPackages: react: ^16.5.2 => 16.5.2 react-dom: ^16.5.2 => 16.5.2 react-scripts: ^2.0.3 => 2.0.5 npmGlobalPackages: create-react-app: Not Found

Steps to Reproduce

  1. Add a condition script in your public/index.html file based on an env variable:
<script>
      '%REACT_APP_ENV%' === 'production' ?  console.log('production') : console.log('not production')
</script>
  1. Set a value for that env variable at build time: REACT_APP_ENV=production react-scripts build
  2. Inspect build/index.html

Expected Behavior

You should see

<script>console.log('production')</script>

Actual Behavior

you see:

<script>console.log('not production')</script>

marco-gagliardi avatar Oct 18 '18 12:10 marco-gagliardi

I can't give a satisfying reason as to why this is happening, but I can give a fix.

<script>
      '%REACT_APP_ENV%'.toString() === 'production' ?  console.log('production') : console.log('not production')
</script>

I'm not sure why we would have to add toString() because if you check the types on both '%REACT_APP_ENV%' and 'production' they're both strings. And the values are both 'production'. But as soon as I added the toString() it worked as expected.

jtwebb avatar Oct 18 '18 13:10 jtwebb

Maybe they are not at build time, when the condition is evaluated. Thanks for the temporary fix though!

marco-gagliardi avatar Oct 18 '18 13:10 marco-gagliardi

+1 Have the same issue.

        console.log('%REACT_APP_CONFIGURATION_BEHAVIOR%');
        console.log('web');
        console.log('%REACT_APP_CONFIGURATION_BEHAVIOR%' == 'web');

got => web web false

It looks like the environements variables have differents values / are not set inside a build tool (probably webpack). Adding ".toString()" probably delay the evaluation of the expression at runtime

Note: I'm using "react-scripts": "2.1.1",

Poyoman39 avatar Nov 07 '18 12:11 Poyoman39

This issue has been automatically marked as stale because it has not had any recent activity. It will be closed in 5 days if no further activity occurs.

stale[bot] avatar Dec 08 '18 15:12 stale[bot]

This issue has been automatically closed because it has not had any recent activity. If you have a question or comment, please open a new issue.

stale[bot] avatar Dec 13 '18 15:12 stale[bot]

console.log('%REACT_APP_LOAD_STUFF%' === 'true') still returns false.

andreisocaciu avatar Dec 14 '18 15:12 andreisocaciu