examples icon indicating copy to clipboard operation
examples copied to clipboard

REST (React): "msw" is included in the production bundle

Open kettanaito opened this issue 5 years ago • 5 comments
trafficstars

One of the users has reported that msw package is included in the production bundle of the rest-react example.

Expected behavior

msw must not be included in the production bundle.

kettanaito avatar Jun 06 '20 18:06 kettanaito

I saw Kent run into this on stream too, but possibly for different reasons. The reason I ran into it was that I assigned process.env.NODE_ENV to another variable, which doesn't work apparently (I vaguely remember knowing that once upon a time, but don't recall the reasoning behind it).

👍🏻 msw not in production bundle:

if (process.env.NODE_ENV === 'test' || process.env.NODE_ENV === 'development') {
  const { worker } = require('./mocks')
  worker.start()
}

👎🏻 msw in production bundle:

const isDevOrTest = process.env.NODE_ENV === 'test' || process.env.NODE_ENV === 'development'
if (isDevOrTest) {
  const { worker } = require('./mocks')
  worker.start()
}

(edit: note the example works just fine unmodified, so that was an invalid report)

wKovacs64 avatar Jun 06 '20 20:06 wKovacs64

@wKovacs64

if (process.env.NODE_ENV === 'test' || process.env.NODE_ENV === 'development') {
  const { worker } = require('./mocks')
  worker.start()
}

This allows the bundler to eliminate the dead code paths, since it will be transformed to:

if (false || false) { // Will never be true
  const { worker } = require('./mocks')
  worker.start()
}

If the if statement can never be true, it will be removed from the bundle. By assigning the ENV variable to another variable first, it would require runtime analysis of the code to determine if it can be eliminated.

const isDevOrTest = false || false
if (isDevOrTest) { // Won't know the value `isDevOrTest` without running the code
  const { worker } = require('./mocks')
  worker.start()
}

thebuilder avatar Jul 13 '20 12:07 thebuilder

@thebuilder There we go, that sounds familiar. Thanks for the explanation!

wKovacs64 avatar Jul 13 '20 14:07 wKovacs64

We need to add an automated test that asserts the msw is not bundled when built a full example like this. Anybody interested in this can pick this up, otherwise I will push something similar in some time. Thanks everybody for discussion on this!

kettanaito avatar Aug 16 '20 10:08 kettanaito

Hey, any update on this? if it's not, can I pick this up?

alishi973 avatar Feb 22 '24 09:02 alishi973