Bad news first: It slightly sucks.
The relevant background info is that there are Javascript and Typescript. Typescript needs to be compiled down to Javascript before it can run in the browser. That’s what the Typescript compiler can do.
The other relevant bit is modules and dependencies. These days, ES modules are the standard way of dealing with them, and npm is the standard package manager. Frustratingly, this part has lots of quirks and weirdness.
From what I know, and from what I can find online, Typescript will not deal with compiling libraries from node_modules
. But okay, no problem, after all they should already be fully functional Javascript. And we just need to import them as ES modules, which the browser understands.
So we write
import { FreeCamera } from "@babylonjs/core/Cameras/freeCamera";
No dice. The browser has no idea where @babylonjs/core
could be. So we whip out import maps and tell it “look in the node_modules folder”.
<script type="importmap">
{
"imports": {
"@babylonjs/core/": "./node_modules/@babylonjs/core/",
"@babylonjs/loaders/": "./node_modules/@babylonjs/loaders/",
"@babylonjs/materials/": "./node_modules/@babylonjs/materials/"
}
}
</script>
Lovely, this should work.
Nope, the browser is still horribly confused.
import { FreeCamera } from "@babylonjs/core/Cameras/freeCamera";
does not include a file extension. So while Typescript automatically figures out what to look at, the browser does not.
Okay, we begrudgingly accept that and write
import { FreeCamera } from "@babylonjs/core/Cameras/freeCamera.js";
And with a bit of fiddling, and using the latest standards to simplify it as much as possible, we get this barebones setup
a.zip (2.9 KB)
I think it works. I don’t know if the sphere should be black, but I’ll take it.
And finally, my future recommendation: Once you feel like you’ve learned enough, and want to go a step further, I do recommend looking at bundlers. They solve the problem of “taking your code, and giving you something that you can actually put on a HTTP server”. And you get a few other niceties, like “hot reloading”, “stuff just working, even when a library has a terribly cursed setup”, …
As for bundlers, the currently nicest one is Vite. It’s relatively simple to set up, and has sensible defaults, unlike some others.