Setting up your dev environment to work with Three.js

It's easy to get started developing with Three.js in a modern way

A focus on a modern dev environment

In principle, you can just drop a script tag into your header that references the three.js library and you're good to go. For simple projects, this can work just fine. Today, you'll have to at least use an importmap, as Three.js is built using modules.

javascript
<script type="importmap">
    {
        "imports": {
            "three": "https://unpkg.com/three@0.160.0/build/three.module.js"
        }
    }
</script>

<script type="module">
    import * as THREE from 'three';

    // Your three.js logic
</script>

But, modern web development doesn't really work that way. We expect all sorts of niceties like hot loading, imports, etc. At the bare minimum, I recommend that you use Vite (pronounced "veet"). It's easy to set up and use for development purposes. When you're ready, it's super straightforward to deploy. Win-win.

Setting up Vite

You'll need at least Node.js and NPM installed to get started. There are plenty of resources online for how to do this, so I won't duplicate them here. In all likelihood, if you're interested in building something with Three.js, you already know and use it.

Open your terminal and run the following commands to create your project:

bash
# Create the project
npm create vite@latest my-three-project -- --template vanilla-ts

# Enter the folder
cd my-three-project

# Install Three.js
npm install three
npm install --save-dev @types/three

Why TypeScript? Because that's where the industry is these days. I started when JS was the default and it's worth migrating to TS. Just do it.

Project Structure and CSS setup

A clean 3D project usually looks like this:

  • index.html: The entry point.
  • src/main.ts: Where our Three.js logic lives.
  • src/style.css: To make the canvas fill the screen.
  • public/: This is where you will put your 3D models (.glb files) and textures.

You'll need a clean canvas to work on, so your default CSS can be something like:

css
/* Remove default spacing and hide scrollbars */
body {
  margin: 0;
  padding: 0;
  overflow: hidden; 
  background-color: #000; /* A dark background prevents white flashes */
}

/* Make the 3D canvas responsive */
canvas {
  display: block;
  width: 100vw;
  height: 100vh;
}

Vite uses Hot Module Replacement (HMR). Because 3D scenes can become "heavy" with large models, Vite only replaces the code you changed without refreshing the entire browser tab. This keeps your development "flow" unbroken. To run your new project, just open your terminal at the root of your project and type:

bash
npm run dev

Vite will run and drop you a link to your new dev environment. You should be good to go.

Succesfully running Vite

You can click on the link in your terminal or manually open http://localhost:5173 to get started.

←   Why Three.js?Hello Cube   →