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 import
ed.
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.
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';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With