Chris
Chris

Reputation: 6182

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.

Upvotes: 8

Views: 5480

Answers (2)

backspaces
backspaces

Reputation: 3942

I believe your problem is that you need to run your import from the THREE src/ tree which is not in the build/ dir, you'd need to clone THREE to have a local src/ tree against which your application runs.

In particular, you could use src/Three.js which is a giant exporter of all the THREE modules. Or simply change your imports to refer to the src//module.js.

Then rollup would have the individual modules against which to run and thus omit unused code.

Edit: see https://github.com/mrdoob/three.js/issues/10328#issuecomment-290233801 for more

Upvotes: 1

Martin Schuhfuß
Martin Schuhfuß

Reputation: 6986

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.

Upvotes: 4

Related Questions