ThreeJS Installation

You can use npm and modern build tools to install three.js, or you can get started quickly with static hosting or a CDN. Installing from npm is the best option for the majority of users.

Whichever option you select, make sure that all files are imported from the same version of the library. Combining files from different sources may result in duplicate code or even break the application in unexpected ways.

All three.js installation methods rely on ES modules (see Eloquent JavaScript: ECMAScript Modules), which allow you to include only the parts of the library that are required in the final project.

Install from npm

To install the three npm modules, launch a terminal window in your project's directory and type:

npm install --save three

The installation package will be downloaded and installed. Then you can incorporate it into your code:

// Option 1: Import the entire three.js core library.
import * as THREE from 'three';


const scene = new THREE.Scene();
// Option 2: Import just the parts you need.
import { Scene } from 'three';


const scene = new Scene();

When you install from npm, you'll almost always use a bundling tool to combine all of the packages your project requires into a single JavaScript file. While any modern JavaScript bundler can be used with three.js, webpack is the most popular option.

Not all features are directly accessible via the three modules (also called a "bare import"). Controls, loaders, and post-processing effects, among other popular library components, must be imported from the examples/jsm subfolder.

Install from CDN or Static Hosting

The three.js library can be used without a build system by uploading files to your own web server or by using a CDN that already exists.

Because the library is based on ES modules, any script that refers to it must include the type="module" attribute, as shown below:

<script type="module">


  // Find the latest version by visiting https://cdn.skypack.dev/three.


  import * as THREE from 'https://cdn.skypack.dev/three@<version>';


  const scene = new THREE.Scene();


</script>

Examples

Three.js's core focuses on the most important components of a 3D engine. The examples/jsm directory contains a plethora of other useful components, such as controls, loaders, and post-processing effects. They're called "examples" because, while they can be used as-is, they're also meant to be remixed and customized. These components are always in sync with the core library, whereas comparable third-party packages on npm are maintained by different people and may be out of date.

Exemplifications do not need to be installed separately, but they must be imported separately. If three.js was installed with npm, you can use the following command to load the OrbitControls component:

import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';


const controls = new OrbitControls();
If three.js was installed from a CDN, use the same CDN to install other components:


<script type="module">


  // Find the latest version by visiting https://cdn.skypack.dev/three.


  import { OrbitControls } from 'https://cdn.skypack.dev/three@<version>/examples/jsm/controls/OrbitControls.js';


  const controls = new OrbitControls();


</script>

It is critical that all files use the same version number. Do not import examples from different versions or use examples from versions other than the three.js library itself.

Compatibility

CommonJS Imports

Although most modern JavaScript bundlers support ES modules by default, some older build tools may not. In those cases, you can probably configure the bundler to understand ES modules: Browserify, for example, only requires the babelify plugin.

Import Maps

When installing from npm, the imported paths differ from when installing from static hosting or a CDN. We are aware that this is an ergonomic issue for both user groups. Developers using build tools and bundlers prefer bare package specifiers (e.g. 'three') over relative paths, and files in the examples/ folder make use of relative references to three.module.js that do not conform to this expectation. Those who do not use build tools — whether for quick prototyping, learning, or personal preference — may dislike relative imports, which require specific folder structures and are less forgiving than a global THREE.* namespace.

When import maps become widely available, we hope to replace them with bare package specifiers to the npm package name, 'three.' This more closely matches build tool expectations for npm packages, allowing both groups of users to write exactly the same code when importing a file. Users who prefer not to use build tools can direct all imports to a CDN or static file folder using a simple JSON mapping.

Node.js

Three.js in Node.js can be difficult to use for two reasons:

For starters, because three.js is designed for the web, it relies on browser and DOM APIs that aren't always available in Node.js. Some of these issues can be addressed by using shims such as headless-gl or by replacing components such as TextureLoader with custom alternatives. Other DOM APIs may be deeply entwined with the code that uses them, making them more difficult to work around. We welcome simple and maintainable pull requests to improve Node.js support, but we recommend that you first open an issue to discuss your improvements.

Second, support for ES modules in Node.js is complicated. With require('three'), the core library can now be imported as a CommonJS module in Node.js v12.

Most example components in examples/jsm, on the other hand, cannot. Future Node.js versions may address this, but in the meantime, you may need to use workarounds such as esm to enable your Node.js application to recognize ES modules.


Related Topics

ThreeJS Compatibiliy Check and Running Locally

Even though this is becoming less of an issue, some devices or browsers may still be incompatible with WebGL. The method below enables you to check if it is supported...

3 minutes read.

ThreeJS Layers

A Layers object assigns an Object3D to one or more of the 32 layers numbered 0 to 31 - the layers are internally stored as a bit mask, and all...

1 minute read.

ThreeJS Property Binding and Mixer

PropertyBinding Internally, this holds a reference to real property in the scene graph. Constructor PropertyBinding( rootNode : Object3D, path, parsedPath ) -- rootNode: -- path -- parsedPath (optional) Properties The properties are as follows: .path : Number.parsedPath...

2 minutes read.

ThreeJS Audio

It is used to create a non-positional (global ) audio object. Code Example: // create an AudioListener and add it to the camera const listener = new THREE.AudioListener(); camera.add( listener ); // create a global...

6 minutes read.

ThreeJS Updating Things

If an item has been added to the scene with the specified code, it will immediately update its matrices. const object = new THREE.Object3D(); scene.add( object ); or, if they are the child...

4 minutes read.

ThreeJS Shadows

LightShadow Serves as a base class for the other shadow classes. Constructor LightShadow( camera : Camera ) camera - the light's view of the world. Create a new LightShadow. This is not intended to be...

7 minutes read.

ThreeJS Disposing an Object

The disposal of unwanted library entities is a crucial component of improving performance and avoiding memory leaks in your programme. When you create a three.js type instance, you set aside...

4 minutes read.

ThreeJS Lines and Texts

Drawing Lines Let's say you want to draw a line or a circle, not a wireframe Mesh. First, we need to set up the renderer, scene, and camera. Here is the...

3 minutes read.

ThreeJS Object3D

This is the base class for most three.js objects, and it provides a set of properties and methods for manipulating objects in 3D space. It should be noted that this can...

9 minutes read.

ThreeJS Interpolant

CubicInterpolant Code Example const interpolant = new THREE.CubicInterpolant(new Float32Array( 2 ),new Float32Array( 2 ),1,new Float32Array( 1 ));interpolant.evaluate( 0.5 ); Constructor CubicInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) parameterPositions -- array of positions sampleValues -- array of samples sampleSize...

2 minutes read.

ThreeJS Uniform

Uniforms are global GLSL variables. They are passed to shader programs. Code Example When declaring a uniform of a ShaderMaterial, it is declared by value or by object. uniforms: { time: { value: 1.0...

2 minutes read.

ThreeJS Matrix Transformations

Three.js encodes 3D transformations using matrices for translations (position), rotations, and scaling. Every Object3D instance has a matrix that records the location, rotation, and scale of the object. This page...

2 minutes read.

ThreeJS Testing with npm

This article explains how to install three.js in a node.js environment so that automated tests may be run. Tests can be done manually or with the help of automated CI...

4 minutes read.

ThreeJS Loader 1

AnimationLoader Class for loading AnimationClips in JSON format. This uses the FileLoader internally for loading files. Code Example // instantiate a loader const loader = new THREE.AnimationLoader(); // load a resource loader.load( // resource URL 'animations/animation.js', // onLoad callback function...

8 minutes read.

ThreeJS Cameras

ArrayCamera ArrayCamera can be used to render a scene using a preset group of cameras quickly. This is an important feature of VR scene rendering performance. An array of sub cameras is...

6 minutes read.

ThreeJS BufferGeometry

A mesh, line, or point geometry representation. Included within buffers are vertex positions, face indices, normals, colours, UVs, and custom attributes, lowering the cost of passing all of this data...

5 minutes read.

ThreeJS Loaders 2

ImageBitmapLoader A loader that converts an image to an ImageBitmap. An ImageBitmap provides an asynchronous and resource-efficient path for preparing textures for WebGL rendering. ImageBitmapLoader, unlike FileLoader, does not prevent multiple concurrent...

8 minutes read.

ThreeJS InterleavedBuffer

The term "interleaved" refers to the packing of multiple attributes, possibly of different types (e.g., position, normal, uv, colour) into a single array buffer. Constructor InterleavedBuffer( array : TypedArray, stride : Integer...

3 minutes read.

ThreeJS Installation

You can use npm and modern build tools to install three.js, or you can get started quickly with static hosting or a CDN. Installing from npm is the best option...

4 minutes read.

ThreeJS Math

Box2 Represents an axis-aligned bounding box (AABB) in 2D space. Constructor Box2( min : Vector2, max : Vector2 ) min - (optional) Vector2 representing the lower (x, y) boundary of the box. Default is...

48 minutes read.