Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 39 ยท Performance and Frameworks

WebGPU, TSL and Three.js Build Tools

Try WebGPURenderer and Three Shading Language (TSL) in Three.js, check capabilities, then ship real projects with npm, Vite, tree shaking, code splitting and TypeScript types.

Two things decide how far you can take a Three.js project beyond the examples in a tutorial: what the GPU can do and how you package your code. For the first, Three.js is moving from WebGL to WebGPU, the newer graphics API, and offers a new shader language called TSL that works on both. For the second, real sites need a build tool, a package manager and a deployment plan rather than a pinned CDN link.

This final lesson of the chapter introduces WebGPURenderer and TSL with runnable examples, and then walks through the production setup: npm, Vite, tree shaking, splitting, TypeScript and shipping assets.

WebGL and WebGPU

WebGL (based on OpenGL ES) has powered the web for over a decade and is what WebGLRenderer uses. It is old in design: state is global, there are no real compute shaders, and the CPU pays for many small calls. WebGPU is the successor, modeled on Vulkan, Metal and Direct3D 12. It has explicit pipelines, lower CPU overhead, compute shaders (general GPU programs, no more ping-pong textures) and storage buffers.

Three.js ships a second renderer, WebGPURenderer, in the three/webgpu entry point. It uses WebGPU when the browser supports it and automatically falls back to a WebGL 2 backend otherwise, so one code base works everywhere. The classic WebGLRenderer is still fully supported and remains the safe default for production in most projects; reach for WebGPURenderer when you need compute shaders, want TSL, or are building something at the edge of performance.

Two renderers, one library

WebGLRenderer Stable, universal, GLSL shaders
WebGPURenderer WebGPU first, WebGL 2 fallback
Compute Real compute shaders on WebGPU
TSL One shader language for both

Imports: three for WebGL, three/webgpu and three/tsl for the new stack.

1 / 2

TSL: Three Shading Language

Writing GLSL for WebGL and WGSL (WebGPU's language) for WebGPU would double the work. TSL is a JavaScript-based shader language: you build shader logic with function calls and operators-as-methods, and Three.js compiles it to GLSL or WGSL depending on the backend. TSL values are nodes: time, uv(), positionLocal and color('#f00') are nodes you combine with .add(), .mul(), sin() and mix().

JavaScript
import { color, time, sin, mix, uv, positionLocal, vec3 } from 'three/tsl';

material.colorNode = mix(color('#ff3366'), color('#33ccff'), sin(time.add(uv().y.mul(6))).mul(0.5).add(0.5));
material.positionNode = positionLocal.add(vec3(0, sin(time.add(positionLocal.x.mul(3))).mul(0.1), 0));

Node materials (MeshStandardNodeMaterial, MeshBasicNodeMaterial, ...) expose slots such as colorNode, positionNode, normalNode, emissiveNode and opacityNode. You fill the slots you care about and the rest of the material (PBR lighting, shadows, fog) keeps working: it is the clean version of the onBeforeCompile trick from the vertex shader lesson.

WebGPURenderer with a TSL material

The shader code never mentions GLSL or WGSL, yet it animates entirely on the GPU. Which backend you see depends on your browser: Chrome, Edge, Safari and recent Firefox expose WebGPU in many setups, and the page keeps working in WebGL 2 when they do not.

TSL functions and uniforms

Reusable logic goes into Fn, and values you change from JavaScript become uniform nodes. This example builds a stepped (toon-style) light on a standard material using the view-space normal, with the light direction and number of bands as uniforms.

A TSL function with uniforms

Changing bands.value after two seconds re-colors the object without recompiling anything. Fn functions can take parameters, contain loops and conditionals (If, Loop), and call each other.

A taste of what WebGPU adds, as a read-only snippet. Compute shaders run arbitrary parallel code on storage buffers, for example moving 100,000 particles with no CPU work and no ping-pong textures:

JavaScript
import { storage, instanceIndex, Fn, vec3 } from 'three/tsl';

const positions = storage(new THREE.StorageInstancedBufferAttribute(count, 3), 'vec3', count);

const update = Fn(() => {
  const p = positions.element(instanceIndex);
  p.addAssign(vec3(0, -0.01, 0));            // gravity for every particle, in parallel
})().compute(count);

renderer.setAnimationLoop(() => renderer.compute(update));   // dispatch, then render as usual

Compute needs a real WebGPU backend, so it is shown here read-only. For stability and broad browser support, plan a WebGL fallback for important production features.

Checking what the device can do

Before using heavy features, read the capabilities. The classic renderer reports many limits:

Device capability report

Use these facts to choose settings: lower resolution and fewer effects when maxTextureSize is small, skip compute when WebGPU is missing, and never rely on a single device's results.

From CDN to a real project

The pinned CDN link and import map used in this tutorial are for learning. A production project installs Three.js with a package manager and bundles it.

Terminal
npm create vite@latest my-3d-app -- --template vanilla
cd my-3d-app
npm install three
npm install --save-dev @types/three   # only needed for TypeScript
npm run dev

Then you import exactly like in the examples, minus the import map:

JavaScript
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';

Why a bundler (Vite, webpack, Rollup, esbuild, Parcel)?

  • Tree shaking: only the parts of Three.js you use end up in the bundle. Prefer named imports (import { WebGLRenderer, Scene } from 'three') for the best result; the full library is around 700 KB minified, 180 KB or so gzipped, and a typical app ships less.
  • Hot reload: edit a shader or a color and see it instantly.
  • Asset handling: import models and textures so the bundler fingerprints them: import robotUrl from './robot.glb?url' (Vite).
  • Code splitting: load heavy features only when needed: const { GLTFLoader } = await import('three/addons/loaders/GLTFLoader.js'); and load the 3D page's bundle only when a user visits it.
  • TypeScript: @types/three gives completion and type errors for the whole API. Match its version to your three version.

A few deployment notes:

  1. Serve .glb, .ktx2 and .js with compression (gzip or Brotli); already-compressed formats (Draco, KTX2) gain little.
  2. Use long cache lifetimes with hashed filenames, so returning visitors load nothing.
  3. Put big models and textures on a CDN with CORS headers (Access-Control-Allow-Origin), otherwise the WebGL texture upload is blocked.
  4. Host Draco, Basis and Meshopt decoder files yourself (copy them from three/examples/jsm/libs/), do not rely on third-party URLs.
  5. Show a lightweight loading state with a LoadingManager, and a static poster image when WebGL is unavailable.
  6. Handle context loss: listen for webglcontextlost on the canvas, call preventDefault(), and rebuild or reload on webglcontextrestored.

Finally, upgrade deliberately. Three.js releases monthly and does not follow semantic versioning: minor releases can rename or remove APIs. Read the migration guide on the project wiki when you bump the version, and keep versions of related packages (@react-three/fiber, postprocessing, loaders) compatible.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does WebGPURenderer do when the browser has no WebGPU support?

    WebGPURenderer chooses WebGPU if available and otherwise runs on its WebGL 2 backend, so the same code works.
  2. 2. What is TSL?

    Three Shading Language builds shader logic from JavaScript node functions and generates backend-specific shader code.
  3. 3. Which feature is a major addition of WebGPU compared to WebGL?

    WebGPU supports general-purpose compute, avoiding workarounds such as ping-pong render targets.
  4. 4. Why prefer named imports like import { WebGLRenderer } from 'three' in a bundled app?

    Bundlers remove code that is never imported, which keeps the download smaller.

Summary

  • WebGPURenderer (from three/webgpu) uses WebGPU when present and falls back to WebGL 2; the classic WebGLRenderer remains the stable default.
  • TSL builds shaders from JavaScript nodes (colorNode, positionNode, Fn, uniform), compiled to GLSL or WGSL; compute shaders need WebGPU.
  • Read renderer.capabilities and feature-detect before relying on advanced features.
  • Production projects use npm, a bundler such as Vite, tree shaking, code splitting, @types/three, hosted decoders, compression, CDN caching and context-loss handling.
  • Pin and upgrade Three.js versions deliberately, because releases can change APIs.

Next: Project: A Solar System