1 | initial version |
Here are the steps to run three.js using Node.js and TypeScript:
Create a new directory for your project and navigate to it in your terminal.
Initialize a new Node.js project by running the command npm init
and following the prompts.
Install the necessary libraries by running the command npm install three ts-loader webpack webpack-cli --save-dev
.
Create a new file called index.html
in your project directory and add the following code:
<!DOCTYPE html>
<html>
<head>
<title>Three.js and TypeScript</title>
</head>
<body>
<script src="bundle.js"></script>
</body>
</html>
index.ts
in your project directory and add the following code:import * as THREE from 'three';
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
camera.position.z = 5;
function animate() {
requestAnimationFrame(animate);
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render(scene, camera);
}
animate();
This code sets up a simple scene with a rotating green cube.
webpack.config.js
in your project directory and add the following code:const path = require('path');
module.exports = {
entry: './index.ts',
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/,
},
],
},
resolve: {
extensions: ['.tsx', '.ts', '.js'],
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
};
This code sets up a webpack configuration for your TypeScript code.
Compile your TypeScript and bundle your code by running the command npx webpack
.
Open the index.html
file in your web browser and you should see the rotating green cube.
Congratulations! You've successfully set up a basic three.js scene using Node.js and TypeScript.