0% found this document useful (0 votes)
34 views3 pages

Installing Three.js: A Quick Guide

This document outlines the installation and project structure for a three.js application, including the necessary HTML and JavaScript files. It provides two options for setting up the project: using npm with a build tool like Vite or importing three.js from a CDN. Additionally, it discusses how to manage dependencies, use addons, and prepare the application for production deployment.

Uploaded by

babbba48
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views3 pages

Installing Three.js: A Quick Guide

This document outlines the installation and project structure for a three.js application, including the necessary HTML and JavaScript files. It provides two options for setting up the project: using npm with a build tool like Vite or importing three.js from a CDN. Additionally, it discusses how to manage dependencies, use addons, and prepare the application for production deployment.

Uploaded by

babbba48
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

nstallation

Project structure
Every [Link] project needs at least one HTML file to define the webpage, and a
JavaScript file to run your [Link] code. The structure and naming choices below
aren't required, but will be used throughout this guide for consistency.

[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>My first [Link] app</title>
<style>
body { margin: 0; }
</style>
</head>
<body>
<script type="module" src="/[Link]"></script>
</body>
</html>
[Link]
import * as THREE from 'three';

...
public/
The public/ folder is sometimes also called a "static" folder, because the files it
contains are pushed to the website unchanged. Usually textures, audio, and 3D
models will go here.
Now that we've set up the basic project structure, we need a way to run the project
locally and access it through a web browser. Installation and local development can
be accomplished with npm and a build tool, or by importing [Link] from a CDN.
Both options are explained in the sections below.

Option 1: Install with NPM and a build tool


Development
Installing from the npm package registry and using a build tool is the recommended
approach for most users — the more dependencies your project needs, the more likely
you are to run into problems that the static hosting cannot easily resolve. With a
build tool, importing local JavaScript files and npm packages should work out of
the box, without import maps.

Install [Link]. We'll need it to load manage dependencies and to run our build
tool.
Install [Link] and a build tool, Vite, using a terminal in your project folder.
Vite will be used during development, but it isn't part of the final webpage. If
you prefer to use another build tool, that's fine — we support modern build tools
that can import ES Modules.

# [Link]
npm install --save three

# vite
npm install --save-dev vite
Installation added node_modules/ and [Link] to my project. What are they?
Improve your editor auto-completion with jsconfig or tsconfig
From your terminal, run:
npx vite
What is npx?
If everything went well, you'll see a URL like [Link] appear in your
terminal, and can open that URL to see your web application.
The page will be blank — you're ready to create a scene.

If you want to learn more about these tools before you continue, see:

[Link] journey: Local Server


Vite: Command Line Interface
MDN: Package management basics
Production
Later, when you're ready to deploy your web application, you'll just need to tell
Vite to run a production build — npx vite build. Everything used by the application
will be compiled, optimized, and copied into the dist/ folder. The contents of that
folder are ready to be hosted on your website.

Option 2: Import from a CDN


Development
Installing without build tools will require some changes to the project structure
given above.

We imported code from 'three' (an npm package) in [Link], and web browsers don't
know what that means. In [Link] we'll need to add an import map defining where
to get the package. Put the code below inside the <head></head> tag, after the
styles.

<script type="importmap">
{
"imports": {
"three":
"[Link]
"three/addons/": "[Link]
}
}
</script>
Don't forget to replace <version> with an actual version of [Link], like
"v0.149.0". The most recent version can be found on the npm version list.

We'll also need to run a local server to host these files at URL where the web
browser can access them. While it's technically possible to double-click an HTML
file and open it in your browser, important features that we'll later implement, do
not work when the page is opened this way, for security reasons.

Install [Link], then run serve to start a local server in the project's directory:

npx serve .
If everything went well, you'll see a URL like [Link] appear in your
terminal, and can open that URL to see your web application.
The page will be blank — you're ready to create a scene.

Many other local static servers are available — some use different languages
instead of [Link], and others are desktop applications. They all work basically
the same way, and we've provided a few alternatives below.

More local servers


Production
When you're ready to deploy your web application, push the source files to your web
hosting provider — no need to build or compile anything. The downside of that
tradeoff is that you'll need to be careful to keep the import map updated with any
dependencies (and dependencies of dependencies!) that your application requires. If
the CDN hosting your dependencies goes down temporarily, your website will stop
working too.

IMPORTANT: Import all dependencies from the same version of [Link], and from the
same CDN. Mixing files from different sources may cause duplicate code to be
included, or even break the application in unexpected ways.

Addons
Out of the box, [Link] includes the fundamentals of a 3D engine. Other [Link]
components — such as controls, loaders, and post-processing effects — are part of
the addons/ directory. Addons do not need to be installed separately, but do need
to be imported separately.

The example below shows how to import [Link] with the OrbitControls and
GLTFLoader addons. Where necessary, this will also be mentioned in each addon's
documentation or examples.

import * as THREE from 'three';


import { OrbitControls } from 'three/addons/controls/[Link]';
import { GLTFLoader } from 'three/addons/loaders/[Link]';

const controls = new OrbitControls( camera, [Link] );


const loader = new GLTFLoader();
Some excellent third-party projects are available for [Link], too. These need to
be installed separately — see Libraries and Plugins.

Next Steps
You're now ready to create a sc

Common questions

Powered by AI

Installing three.js using npm offers better local dependency management, making it easier to handle complex projects with multiple dependencies. It integrates well with modern build tools, which aid in module bundling and optimization. However, it requires setting up Node.js and a build tool like Vite, which can have a steeper learning curve for beginners. On the other hand, using a CDN simplifies initial setup by directly importing the library from a URL, which can be ideal for smaller or simpler projects. The trade-off is the dependency on external servers, where downtime or version mismatches could break the application. Additionally, using a CDN requires an import map, increasing project complexity .

The recommended project structure for a basic three.js application includes at least one HTML file, typically named index.html, and a JavaScript file, commonly named main.js. The HTML file defines the webpage, while the JavaScript file contains the three.js code. This structure is considered best practice because it maintains separation of concerns, keeping the HTML for structure and the JS for behavior. Additionally, including a public folder for static assets ensures that textures, audio, and 3D models are easily accessible and correctly loaded into the application without modification .

To switch a three.js project to production mode using Vite, developers need to build the application using the command npx vite build. This compiles, optimizes, and copies all necessary files into the dist/ folder. The contents of this folder are then ready to be hosted on a website without further modification. This process ensures that all code is minified and bundled appropriately for optimal performance in a production environment .

The static folder, often named public, benefits file management in three.js projects by serving as a central repository for unchanging or static assets like textures, audio files, and 3D models. By isolating these files, developers ensure they are readily accessible and not altered during build processes, maintaining consistency in how these resources are deployed. This approach improves project organization and efficiency when loading these assets at runtime .

Addons in a three.js application, such as orbit controls and loaders, extend the basic capabilities of the core library by providing additional functionalities like camera controls and 3D model loading. When importing addons, developers need to ensure they are compatible with the three.js version being used to avoid potential conflicts. Addons do not require separate installations, but must be explicitly imported, often from a specific directory structure, ensuring that they are correctly referenced in the module import statements .

Mixing dependencies from different sources in three.js projects can lead to issues such as code duplication, version conflicts, or unexpected behavior due to incompatible module versions. This can result in runtime errors or application instability. To avoid these issues, developers should ensure all dependencies are imported from the same version of three.js and are sourced from a single CDN or package manager. This consistent approach prevents incompatible code from being mixed and reduces the likelihood of errors .

Using a build tool like Vite during three.js development is important because it simplifies dependency management and module importation. For projects with multiple dependencies, a build tool resolves potential conflicts and issues that static hosting alone cannot handle. Vite allows developers to seamlessly import local JavaScript files and npm packages, optimizing the development workflow. Additionally, it provides hot module replacement, improving development efficiency by allowing instant updates in the browser without full reloads, thus streamlining the iterative development process .

Updating three.js dependencies via a CDN involves changing the version number in the import map script in the HTML file to match the desired version. It is critical to ensure all three.js-related imports are updated simultaneously to avoid version conflicts. Developers should check the availability of the new version on the CDN and assess any breaking changes or new features that could affect their application. This cautious approach minimizes the risk of introducing bugs and ensures all imports are synchronized .

npx is a tool provided by Node.js that allows for the execution of Node packages directly from the npm registry without installing them locally. In a three.js project, npx can be used to run development tools like Vite, which facilitates server deployment and live reloading during the development process. By executing npx vite, a local development server is launched, allowing the developer to open the application in a browser at the given localhost URL. This method benefits from avoiding global installs, keeping the environment clean and reducing setup overhead .

A local server is necessary when developing a three.js application because it overcomes security limitations that browsers impose when accessing certain features directly from the file protocol. Without a server, features like module imports and cross-origin requests may not work correctly, leading to errors. Using a CDN for three.js libraries amplifies this issue, as it relies heavily on import maps and network requests that are not feasible in an offline or file-based environment. A local server enables these functions, allowing for a seamless testing environment .

You might also like