Skip to content

Non-dead JavaScript is removed during build #7448

Open
@salomvary

Description

@salomvary

Describe the bug

react-scripts build seems to be removing inline JavaScript code from index.html that should not be removed. It happens to code paths that are conditional and the condition contains a build-time '%VARIABLE%'.

Workaround: move the build-time variable outside of the condition.

Did you try recovering your dependencies?

No, it's a newly created project.

Which terms did you search for in User Guide?

NODE_ENV, index.html, variables

Environment

  System:
    OS: macOS 10.14.5
    CPU: (4) x64 Intel(R) Core(TM) i5-5287U CPU @ 2.90GHz
  Binaries:
    Node: 8.16.0 - /usr/local/bin/node
    Yarn: 1.17.3 - /usr/local/bin/yarn
    npm: 6.10.1-salomvary1 - /usr/local/bin/npm
  Browsers:
    Chrome: 75.0.3770.142
    Firefox: 68.0.1
    Safari: 12.1.1
  npmPackages:
    react: ^16.8.6 => 16.8.6 
    react-dom: ^16.8.6 => 16.8.6 
    react-scripts: 3.0.1 => 3.0.1 
  npmGlobalPackages:
    create-react-app: 3.0.1

Steps to reproduce

  1. Create a new app with create-react-app.
  2. Edit public/index.html and add a the snipped below after <body>.
  3. Run npm run build.
  4. Open build/index.html
    <script>
      console.log('%NODE_ENV%');
      var nodeEnv = '%NODE_ENV%';
      if ('%NODE_ENV%' === 'production') {
        console.log('This is production!');
      }
      if (nodeEnv === 'production') {
        console.log('This is REALLY production!');
      }
    </script>

Expected behavior

build/index.html should contain the minified version of the entire snippet with %NODE_ENV% replaced with production.

Actual behavior

This is what build/index.html contains instead (note that the first if block is entirely missing):

<script type="text/javascript">
console.log("production");var nodeEnv="production";"production"===nodeEnv&&console.log("This is REALLY production!")
</script>

Reproducible demo

https://github.com/salomvary/create-react-app-bug

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions