A "Gotcha" When Importing ES6 Modules into Babylon.js using Typescript
This might be clear to more experienced Typescript/Babylon/ES6 devs, but wasn't to me (or my students).
I was looking into the question of importing individual modules from their files, vs importing things from @babylonjs/core
. Finding the right import for a class is currently a pain in Babylon, and if you use a module that relies on side effects from another module you must import it manually (e.g., to use Shadows, you need to import shadowGeneratorSceneComponent
).
In contrast, if you import things directly from @babylonjs/core
, those problems don't surface; you can import ShadowGenerator
without worrying about importing the scene component. The reason for this is that by importing from core directly, you defeat the tree shaking feature of modules that results in small builds and downloads, but that guarantees everything you need is imported (along with a bunch of junk you don't need).
For example, on one student project, they needed to import these two things to get shadows working:
import "@babylonjs/core/Lights/Shadows/shadowGeneratorSceneComponent";
import { ShadowGenerator } from "@babylonjs/core/Lights/Shadows/shadowGenerator";
Doing that, for their project (and running npm run build
to create a webpacked .js file containing all dependencies) resulted in a .js file for this project of 1.13MB.
But if I change the import to
import { ShadowGenerator } from "@babylonjs/core";
it works, but the build is now 2.5x as big, 2.80MB.
Poking into the Typescript source, I assume the reason is that if you import anything from @babylonjs/core
it pulls everything from @babylonjs/core/index.js
.
Anyway, since this was useful for me to learn, I thought others might find it useful.