Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I tree shake Three.js using WebPack or Rollup?

I've got a Three.js scene that only uses a portion of the library.

import {
    Scene,
    PerspectiveCamera,
    WebGLRenderer,
    BoxGeometry,
    MeshBasicMaterial,
    Mesh} from 'three';

But I still end up getting most, if not all, of the entire library (~500Kb minified). Has anyone had any luck with this? I have an example GitHub that shows the code I'm using.

like image 933
Chris Avatar asked Jan 08 '17 22:01

Chris


People also ask

Does webpack have tree shaking?

The webpack. config. js file has a root property named mode . Whenever this property's value is production , it will tree-shake and fully optimize your modules.

How do you make a tree shake?

The principle behind tree shaking is as follows: You declare all of your imports and exports for each of your modules. Your bundler (Webpack, Rollup, and so on) analyzes your dependency tree during the compilation step. Any provably unused code is dropped from the final bundle, or 'tree-shaken'.

How webpack detect the dead code that can help in tree shaking?

It relies on the import and export statements to detect if code modules are exported and imported for use between JavaScript files. In modern JavaScript applications, we use module bundlers (e.g., webpack or Rollup) to automatically remove dead code when bundling multiple JavaScript files into single files.


1 Answers

I'm currently using WebPack2 in a project and switched to using the built-in tree-shaking. Let's walk through the steps:

  • obviously, install current three.js via npm: npm install three
  • in the webpack-config, we need to override what happens when you import {Something} from 'three'; in your code. To do this, I use the alias-setting of the resolver-config to use the alternate module-build that is included with newer three.js versions:

     {
       resolve: {
         extensions: ['.js'],
         modules: [SRC_PATH, 'node_modules'],
         alias: {
           'three': path.join(__dirname, 'node_modules/three/build/three.module.js')
         }
       }
     }
    
  • now, if you're using babel to transpile your javascript, you need to make sure that the plugin that compiles es6-modules to commonjs is not included. Otherwise the babel-tree-shaking simply won't find any es6-modules to shake (in case you are already using the es2015-preset, you can use babel-preset-es2015-native-modules instead). There's some more information about that in this blog-post.

like image 193
Martin Schuhfuß Avatar answered Oct 09 '22 16:10

Martin Schuhfuß