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.
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.
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'.
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.
I'm currently using WebPack2 in a project and switched to using the built-in tree-shaking. Let's walk through the steps:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With