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.
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.
Share Improve this question edited Mar 29, 2018 at 22:33 halfer 20.4k19 gold badges109 silver badges202 bronze badges asked Mar 6, 2018 at 17:02 iQ.iQ. 3,9536 gold badges40 silver badges60 bronze badges 2-
1
Add something that does dead code elimination (
webpack.optimize.UglifyJsPlugin
). – Yury Tarabanko 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 – iQ. Commented Mar 7, 2018 at 12:20
2 Answers
Reset to default 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'
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.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744863975a4597867.html
评论列表(0条)