简体   繁体   中英

Include JS module/file only in development-mode

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:

  • Eject from create-react-app with npm run eject . You may be worried about the maintenance burden but it you look at the create-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 .
  • Go to webpack.config.js (or craco.config.js if using craco)
  • Add an externals field if the app is running in production mode

Should look something like this . In this object add an externals part:

externals: isEnvProduction ? {
   'myApiAdapter' : 'window' // or something else global
} : undefined, 

This will map import('myApiAdapter') to window 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM