2

all, I'm new to Webpack. Currently, I'm facing a question with webpack tree shaking. In CommonJS, webpack cannot do tree shaking because of the require syntax. For example, a program can import packages from below ways but tree shaking cannot be worked,

var a;
if(condition){
    a = require('module1');
}else{
    a = require('module2');
}

Then, tree shaking is based on import static syntax from ES6 modules, package cannot be imported dynamically.

However, in es7, there is a dynamic way to load modules by lazy loading import (module). So, my question is can tree shaking still work if the program contains lazy loading syntax, if webpack can do that, how is this achieved?

Liam
  • 27,717
  • 28
  • 128
  • 190
leo0807
  • 941
  • 1
  • 8
  • 21

1 Answers1

0

As far as I know, no compiler/bundler supports tree shaking dynamically imported modules. Webpack 5 might be slightly better in removing unused code inside dynamically loaded bundles.

You can however do it the old way; Create two html sites, have a shared bundle of JS and page-specific bundle, and just link to the other page.

Jkarttunen
  • 6,764
  • 4
  • 27
  • 29