Hi everyone! I’m working on reducing the final bundle size of an application built with Reactylon.
Currently, a significant amount of code is being included in the consumer’s final bundle because Reactylon uses instanceof
operator to identify the incoming Babylon.js entities and determine how to handle them. For example:
import { Material } from '@babylonjs/core/Materials/material';
import { BaseTexture } from '@babylonjs/core/Materials/Textures/baseTexture';
import { Light } from '@babylonjs/core/Lights/light';
// instance is the Babylon.js entity that i'm dealing with
if (instance instanceof Material) {
// do something relative on Material (e.g. deal with Material or SubMaterial children)
} else if (instance instanceof BaseTexture) {
// do something relative on Texture (attach it on parent Material)
ì} else if (instance instanceof Light) {
// do something relative to Light
}
// and so on...
This method leverages inheritance and works well in terms of structure. However there’s a downside: it forces me (as a consumer of the library) to indirectly import classes into the final bundle that i may never use. For instance, even if my code doesn’t use any textures, the BaseTexture
class still ends up in the final bundle.
To make this more efficient, i’m exploring alternative ways to determine which Babylon.js entity i’m dealing with and i have come up with a few ideas:
- Using the class name (or attaching a
Symbol
in case of missing name due to mangling in production). - Checking for specific properties or methods (duck typing) or relying on some internal Babylon.js markers (e.g.,
_isMesh
).
However, I’m unsure about the robustness of these solutions. Do you have any other approaches in mind or is this a trade-off i simply have to accept?