Skip to content

Tree-shakable Three.js Imports for TresJS #1292

@Jungzl

Description

@Jungzl

Description

Currently, TresJS imports the entire Three.js namespace in Context.vue and registers all exports. This causes bundlers to include the entire Three.js library in the final build, even when the user only uses a small subset of Three.js objects.

For a typical start template provided by pnpm create tres with build config below:

  build: {
    minify: false,
    rolldownOptions: {
      output: {
        codeSplitting: {
          groups: [
            {
              test: /\/three\//,
              name: 'three',
            },
          ],
        },
      },
    },
  },
vite v8.0.0-beta.11 building client environment for production...
✓ 43 modules transformed.
dist/index.html                               0.63 kB │ gzip:   0.36 kB
dist/assets/index-eDIznQ1E.css                0.13 kB │ gzip:   0.11 kB
dist/assets/rolldown-runtime-2YtBIAaz.js      0.31 kB │ gzip:   0.22 kB
dist/assets/index-DZHj7OJD.js               365.31 kB │ gzip:  88.65 kB
dist/assets/three-BurP11D-.js             1,152.04 kB │ gzip: 221.15 kB

If I remove default extend(THREE) and manually register Three.js objects

  extend({
    PerspectiveCamera,
    AmbientLight,
    Mesh,
    BoxGeometry,
    MeshNormalMaterial,
    DirectionalLight,
    AxesHelper,
    GridHelper,
  })
vite v8.0.0-beta.11 building client environment for production...
✓ 43 modules transformed.
dist/index.html                   0.54 kB │ gzip:   0.33 kB
dist/assets/index-eDIznQ1E.css    0.13 kB │ gzip:   0.11 kB
dist/assets/index-Cg3u0u30.js   365.15 kB │ gzip:  88.59 kB
dist/assets/three-DQ5wCXSo.js   783.91 kB │ gzip: 152.88 kB

221.15kB -> 152.88kB is quite BIG!

Suggested solution

Option 1: add a new prop manualExtend to TresCanvas that allows users to opt-out of automatic Three.js namespace registration.

Option 2: provide a plugin that analyzes which Three.js classes are used and auto-imports & tree-shakes accordingly. This might be framework-specific.

Alternative

No response

Additional context

https://github.com/pmndrs/react-three-babel

Validations

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions