Skip to content

Importing Three.js Modules

Tip

This course was updated in 2024. For the newer content, please visit Importing Three.js Modules

Video Lecture

Importing Three.js Modules -->

Description

The core of Three.js is focused on the most important components of the 3D engine.

Many extra modules such as 3D model loaders and controls are part of the examples' directory.

If you want to use these extra modules in your project, then you will need to import them separately.

The ./node_modules/three/examples/jsm/ directory, which was installed as part of Threejs, contains many useful extra modules that you can use in your Threejs projects.

In this lesson, I will show you how to import the OrbitControls into the existing TypeScript project.

Note

Note that we are using the /examples/jsm/ folder instead of the examples/js/ folder. We are using the ES6 module versions of all the example scripts instead of the classic CommonJS imports.

./src/client/client.ts

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'

const scene = new THREE.Scene()

const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000)
camera.position.z = 2

const renderer = new THREE.WebGLRenderer()
renderer.setSize(window.innerWidth, window.innerHeight)
document.body.appendChild(renderer.domElement)

new OrbitControls(camera, renderer.domElement)

const geometry = new THREE.BoxGeometry()
const material = new THREE.MeshBasicMaterial({
  color: 0x00ff00,
  wireframe: true,
})

const cube = new THREE.Mesh(geometry, material)
scene.add(cube)

window.addEventListener('resize', onWindowResize, false)
function onWindowResize() {
  camera.aspect = window.innerWidth / window.innerHeight
  camera.updateProjectionMatrix()
  renderer.setSize(window.innerWidth, window.innerHeight)
  render()
}

function animate() {
  requestAnimationFrame(animate)

  cube.rotation.x += 0.01
  cube.rotation.y += 0.01

  render()
}

function render() {
  renderer.render(scene, camera)
}

animate()

If your project is not currently running,

npm run dev

and visit http://localhost:8080/