8

Webpack will include all of d3.js in the bundle when doing import { select } from 'd3' as seen in the following bundle visualization. The problem can be solved by doing import { select } from 'd3-selection' but this defeats the purpose of automatic tree shaking somewhat.

Tree shaking does appear to work in simple cases on our non-library code.

We use "modules": false in our .babelrc in order to retain the module syntax and use 'module' resolve in our webpack.config.js resolve: { mainFields: ['module', 'browser', 'main'] } in order to select d3's module based code. As you can see the imported node_modules/d3/index.js is partitioned in ES6 modules instead of a monolithic browser bundle or CommonJS export.

Should this be posted as an issue on the webpack github page or am I doing something wrong? This is using all the latest versions of the libraries (d3@4.5.0, webpack@2.2.1, etc)

edit: Seems like this is related to the following issues:

  • Just wanted to comment that I have run into the same issue with Webpack 2.2.1 and d3 4.6.0. Tree shaking does work for other libraries. Please comment if you have found any solution. – Nicd Feb 23 '17 at 07:15
  • Looks like there is a new webpack plugin to handle Common JS. Please see my updated answer. – nickytonline Jul 02 '17 at 19:02
  • While the apparent bug is being fixed (if possible at all) I'd consider importing from a more specific module. E.g. `import {select} from 'd3-selection'`, or even `import select from 'd3-selection/src/select'`. – Francesc Rosas Aug 14 '17 at 15:41

1 Answers1

4

Tree shaking will only work for ES6 modules because they can be statically analyzed. AMD/CommonJS which a lot of libs publish can't be, which is why you're probably not seeing any tree shaking happening. Please see https://advancedweb.hu/2017/02/07/treeshaking

UPDATE: There appears to be a new webpack plugin that is capable of tree shaking Common JS modules, https://github.com/indutny/webpack-common-shake. Please note, that the repo says it's in alpha.

nickytonline
  • 6,855
  • 6
  • 42
  • 76