How can I conditionally import a module only in development mode (in my case the axios-mock-adapter
package). Also the code should not even be present in the production bundle.
Example code I only want to be included during development:
export const mockUpClient = (api: AxiosInstance): void => {
// full api mocking, containing lots and lots of data
}
Now I am importing the module based on the following condition:
if (process.env.NODE_ENV === 'development') {
import("./apiMockAdapter").then((module) => {
module.mockUpClient(api)
})
}
The code is still included in the build, however it is not executed in production mode. How is it possible to completely exlude the code from the production bundle (of course without commenting out the code before every build)?
Update
The above example works fine. Before asking the question, I also imported the file from somewhere else, which led to this behaviour.
The accepted answer explains in detail how webpack will bundle the code & modules.
Basically:
npm run eject
. You may be worried about the maintenance burden but it you look at thecreate-react-app
repo you'll see there are very few meaningful changes in CRA and the upkeep with it is actually higher. If you are insistent on CRA then use craco.webpack.config.js
(orcraco.config.js
if using craco)externals
field if the app is running in production modeShould look something like this. In this object add an externals part:
This will map
import('myApiAdapter')
towindow
in production builds and not include it in the bundle.That said, webpack should see the dynamic import as a point to break the bundle down into chunks, so it's unclear without seeing your actual code why it is included. Making that file external should bypass any such issues.