7

I am trying to load a module conditionally and the condition seems to work however webpack still makes the conditional module part of the bundle when the condition is false, here is the import code:

if (process.env.FEAT_SUPPORT === 'on') {
  require('feature');
  console.log('Enabled')

} else {
  console.log('disabled')
}

Even if the value is not 'on' it still requires the module. I tested this using the log lines and the correct log lines appear when it is on and off.

I am using the Webpack define plugin to set the variable. The main reason for doing the above is to keep the bundle size small and it doesn't seem to be doing it.

2
  • 1
    Add something that does dead code elimination (webpack.optimize.UglifyJsPlugin). Commented Mar 6, 2018 at 17:14
  • I use the webpack production build which doe the optimise and minimise, it removes dead code but doesn't do it for the above case Commented Mar 7, 2018 at 12:20

2 Answers 2

3

(Posted answer on behalf of the question author).

So the above code was almost right, I need to remove the expression and simply use a if(process.env.FEAT_SUPPORT) where FEAT_SUPPORT is replaced by either 'true' or 'false'

Sign up to request clarification or add additional context in comments.

2 Comments

I didn't think this worked - good to know! Been searching for a way to conditionally prevent packages from being bundled for ages.
This unfortunately doesn't seem to work with CRA, since it sets the environment variables as strings and TerserPlugin/UglifyJsPlugin only seem to recognize dead code with explicit booleans.
1

require by design can be invoked in any place in the code, so this will add a new module inside the bundle. If you want to split that require into a separate file you should use require.ensure method, that webpack will split it out for you.

You can use as well the new ES6 import() syntax, that will create the same result.

Please read: dynamic-imports chapter in the webpack docs.

4 Comments

So what I want is still a single bundle and not split into any new files. I wanted my build to generate the bundle with the required module or exclude it based on a build time flag.
In that case, u should use DefinePlugin, that will change your If to false / true, and then with a combination of UglifyJsPlugin, it will be removed in production mode.
So that is what I am doing, the if condition does become false yet the bundle size does not change. I use the webpack -p build which the docs says it uses UglifyJsPlugin, are you recommending I add Uglify separately?
No need, the plugin is enough, you can search for that if in the minified bundle to check if definePlugin is worked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.