javascriptreactjsaxios-mock-adapter

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.


Solution

  • Basically:

    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.