So for example:
import axios from 'axios'
if(process.env.USE_AXIOS) {
axios.get("/");
}
in this Axios should not be bundled from Webpack.
CodePudding user response:
There are probably couple of ways to handle conditional compilation, but one I know it works is to use dynamic imports
// Just to not throw an exception in the snippet
const process = {
env:{
USE_AXIOS: false
}
}
// ------------------------------------------------
// Solution
if (process.env.USE_AXIOS) {
import('axios').then(({default: axios}) => {
if ('get' in axios) {
console.log('axios in use');
}
});
}
full code example is here webpack-conditional-complation
you can examine a produced code
- here is an axios bundled in separated file
- here is a compiled ./src/include-axios-base-on-env.js to with-axios.js with flag USE_AXIOS=true
- here is a compiled ./src/include-axios-base-on-env.js to without-axios.js with flag USE_AXIOS=false