Conditionally required modules included in production build

615 views Asked by At

I have an app based on Create-React-App. During development, I often stand up a mock API server by running a NPM script that sets an environment variable:

"start": "react-scripts start",
"start:mock-api": "cross-env REACT_APP_MOCK_API=true react-scripts start",
"build": "react-scripts build",

That env var determines if the mock server should spin up:

if (process.env.REACT_APP_MOCK_API === "true") {
  /* eslint-disable import/no-extraneous-dependencies */
  const { setupWorker } = require("msw");
  const { handlers } = require("src/mockApi/serverHandlers");

  setupWorker(...handlers).start();
}

I produced a build today and got this message:

The bundle size is significantly larger than recommended

I started snooping around my bundle and unexpectedly came across the uglified invocation of my mock api's setupWorker().start():

"true"===Object({NODE_ENV:"production",PUBLIC_URL:"",WDS_SOCKET_HOST:void 0,WDS_SOCKET_PATH:void 0,WDS_SOCKET_PORT:void 0,FAST_REFRESH:!0,REACT_APP_ENV_NAME:"development"})
.REACT_APP_MOCK_API){var jd=n(54)
.setupWorker,Td=n(424).handlers;jd.apply(void 0,Object(i.a)(Td))
.start()}

I had assumed during a prod build, that path would be eliminated as dead code, but obviously that is not the case. This is problematic as I have references to large JSON files in my mock api, and those are getting pulled into the bundle.

Any thoughts on how I can exclude my mock api module when producing a production build?

1

There are 1 answers

0
Mister Epic On

To exclude those conditionally required modules, it is required we explicitly set the env variable in our build script:

"build": "cross-env REACT_APP_MOCK_API=false react-scripts build"