Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid bundling mock modules on Webpack build?

We are trying to make our React + GraphQL project independent of any other layers in the ecosystem to improve developers experience. In line with that, we have written a thin HOC that wraps Apollo own graphql HOC and uses an internal environment variable to switch between network fetching and mock data. On production builds, all that mock data is, obviously, not used, even if it is imported.

Is there any way to avoid including modules in Webpack's production bundle that you know you are not going to need while keeping everything else the same/not breaking the app?

Something like dynamic import() could do the trick, but that ends up chunking your build rather than omitting what you don't need/want.

UPDATE: The app was created using create-react-app 1.0.17 and later ejected.

like image 850
Nicolás Fantone Avatar asked Nov 25 '17 13:11

Nicolás Fantone


1 Answers

I'm using following dir structure.

api
  index.js
  apimock.js
  apirest.js

In index.js you switch implementation depending on NODE_ENV:

if (process.env.NODE_ENV === 'production') {
  module.exports = require('./apirest');
} else {
  module.exports = require('./apimock');
}

You will need to use webpack DefinePlugin to set NODE_ENV:

new webpack.DefinePlugin({
  'process.env': {
    NODE_ENV: `"${process.env.NODE_ENV || 'development'}"`,
    ENABLE_DEVTOOLS: JSON.stringify(!!process.env.ENABLE_DEVTOOLS)
  }
})

Build command (npm script):

NODE_ENV=production webpack --config webpack.config.js

or for mock implementation:

NODE_ENV=development webpack --config webpack.config.js

Webpack will only bundle single implementation depending on NODE_ENV.

In your component (saga...) you simply import api:

import * as api from 'api';
like image 101
mauron85 Avatar answered Sep 20 '22 07:09

mauron85