Testing and Experimenting with the Examples
Explore the process of setting up, building, and running Three.js example projects, including installing dependencies, using build tools like webpack, and testing 3D scenes in a browser. Understand the project structure and workflow that helps you efficiently create and render your first 3D scene with Three.js.
We'll cover the following...
Install the dependencies
First, we need to download the external libraries. For instance, Three.js is one of the dependencies we need to download.
We need two types of dependencies, one for runtime and the other for development. In the dependencies section (lines 8–19), we have the library three (line 13). This is the primary library for 3D graphics. We also need a build tool to bundle and optimize our projects. In the devDependencies section (lines 20–24), we will use webpack (line 23) for this purpose.
To download all the dependencies, we run the following command:
The preceding command will start downloading all the required JavaScript libraries and store these in the node_modules folder.
Next, we need to build the examples. Doing so will combine our source code and the external libraries into a single file, which we can show in the browser. To build the examples using
npm, we use the following command:
Note that we only have to run the two preceding commands once.
To open these examples, we need a web server. To start a server, simply run the following command:
Note: In the course, we use the playgrounds embedded in the lessons. There is no need for local setup.
Getting started with an example
The output of the above snippets can be tested in the below playground. Click the “Run” button and execute the command in the below-integrated terminal:
npm installnpm run buildnpm run serve
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
// const CopyWebpackPlugin = require('copy-webpack-plugin')
const fs = require('fs').promises
// we should search through the directories in examples, and use
// the name from the files to generate the HtmlWebpackPlugin settings.
const CHAPTER_PREFIX = path.join(__dirname, 'samples/chapters/')
module.exports = async () => {
const { generatedEntries, generatedPlugins } = await getDirectoryEntries()
return {
module: {
rules: [
{
test: /\.glsl$/i,
use: 'raw-loader'
}
]
},
mode: 'development',
entry: {
...generatedEntries
},
devtool: 'inline-source-map',
devServer: {
allowedHosts: 'all',
host: '0.0.0.0',
port: '3000',
// static: ['./dist', './assets']
static: [
{
directory: path.join(__dirname, 'assets'),
publicPath: '/assets'
},
{
directory: path.join(__dirname, 'dist')
}
]
},
plugins: [
...generatedPlugins
],
output: {
filename: 'js/[name].js',
},
optimization: {
splitChunks: {
chunks: 'all'
}
},
experiments: {
asyncWebAssembly: true
}
}
}
const getDirectoryEntries = async () => {
const generatedPlugins = []
const generatedEntries = {}
const chapters = [
'chapter-1'
]
for (const chapter of chapters) {
const entries = await fs.readdir(CHAPTER_PREFIX + chapter, {
withFileTypes: true
})
const candidates = entries.filter((entry) => entry.name.endsWith('.js'))
for (const candidate of candidates) {
const name = path.parse(candidate.name).name
const plugin = new HtmlWebpackPlugin({
filename: chapter + '/' + name + '.html',
chunks: [name],
template: 'template.html'
})
generatedEntries[name] = {
import: CHAPTER_PREFIX + chapter + '/' + candidate.name
}
generatedPlugins.push(plugin)
}
}
return { generatedEntries, generatedPlugins }
}
Note: If you are unable to see the output, please click the “Run” button again.
Let’s change the color of the cube. To do so, find the following code (lines 16–19 in the above playground):
Change it (line 3 in the above snippet) to the following:
Note: After making changes in the playground, click “Run” button to see updates in the output.
A good starting point to understand how everything works together is by looking at the HTML file that we opened in the browser.
Exploring the structure for Three.js application
In this chapter, we’ll look at the source of the geometries.html file. We can do this by looking at the source in the browser or opening the file from the dist/chapter-1 folder in the same location where we built the project.
Note: We can view the
dist/chapter-1/geomerties.htmlfile in the above terminal after stopping the application by using “ctrl+c” (“control+c” on macOS). We need to runcat dist/chapter-1/geomerties.htmlto view the content of the file.
This code is generated when we run the npm run build step. This will combine all the sources and external libraries we’ve used into separate source files (called bundles) and add them to this page. So, we don’t need to do this ourselves. The first three <script> tags (lines 11–13) refer to any of the external libraries we use. Those will be included in the same manner automatically. The only other elements here are <style> (lines 6–10) and <body>. The <style> is used to disable any margins in the page, so we can use the complete browser viewport to show our 3D scenes. Furthermore, we’ll add the 3D scene programmatically into an empty <body> element.
If we do want to add custom HTML elements here, we can, of course, do that. In the project main directory, we can find a template.html file that is used by the build process to create an HTML file for each example in this course. Anything we add there will be added to all the examples.
We won’t dive too deep into how this works since that’s outside the scope of this course. However, if you want to learn more about how this works, a couple of good resources on webpack (which we use for this) are as follows:
The getting started with webpack guide. This site contains a tutorial that explains the reason why we need webpack for JavaScript development, and how the basic concepts work.
Information on the HTML webpack plugin. Here, we can find information on the webpack plugin we use to combine the sources into the separate HTML pages we see when we open the browser after running
npm run buildand then runningnpm run serve.
Note that we don’t have to explicitly initialize our scene or call JavaScript. Whenever we open this page and the geometries.js file is loaded, the JavaScript from that file will run and create our 3D scene. Now that we’ve set up the basic structure, we can create and render our first scene.