examples
examples copied to clipboard
REST (React): "msw" is included in the production bundle
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.
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
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 There we go, that sounds familiar. Thanks for the explanation!
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!
Hey, any update on this? if it's not, can I pick this up?