Using three.js with React, Vue.js, Angular, Svelte, TypeScript and More
In the last chapter, we showed you how to include three.js in a simple web page consisting of just three files: index.html, src/main.js, and styles/main.css. Throughout the book, we’ll continue to use this minimal setup to showcase the applications we build.
We said earlier in the book that our goal is to show you how to build a real-world, professional-quality three.js application. In a world where frameworks are king, it seems like using such a simple web page to showcase our work is at odds with this claim. Fortunately, that’s not the case, since three.js scenes are always displayed within a single HTML
If you wish, you can create this canvas directly in HTML:
However, you can also create the canvas using your favorite framework, whether that’s React, Vue.js, Svelte, or even your own hand-crafted custom framework, and then hand it over to three.js.
In this book, we’ll write code that is framework agnostic, which means you can connect it up to any framework you like. Most web frameworks work by building your app out of discrete, modular components. For example, a React component may be a contact form, or a drop-down menu, or an image gallery. We’ll structure our three.js applications in the same way, so that in the end we have a single top-level component called a
World that creates a three.js scene inside a
<canvas> element. To use this
World component with React, you can wrap it inside a React Component, to use it with Vue.js, you can wrap it inside a Vue Component, to use it with Angular, you can wrap it inside an Angular Component, to use it with Svelte… well, you get the picture. In other words, you can create your main app the React way, or the Angular way, or the Svelte way, and create your three.js app the three.js way, and then connect them up with very little effort.
Of course, you may prefer to write the three.js part of your app the Svelte/Angular/React/Vue.js way as well, which is absolutely possible. In that case, you’ll need to do some work to refactor the code in the book before you can use it, but the theory we cover will remain useful to you.
What About TypeScript?