I’m writing some BABYLON middlewares and I want these libraries to be available for ES6 (with tree shaking) and as a UMD. I did not found a good pattern, let me explain with a simple example :
ES6
import {Matrix} from '@babylonjs/core'
let identity = Matrix.Identity();
UMD
let identity = BABYLON.Matrix.Identity();
I don’t want to duplicate code, it would be a nightmare to maintain, so here was my first try :
import {Matrix} from '@babylonjs/core'
if(window.BABYLON) {
let identity = BABYLON.Matrix.Identity();
}
else {
let identity = Matrix.Identity()
}
Then with webpack or rollup I can set @babylonjs/core as externals for the UMD build and everything works well…BUT it quickly become complicated because I have to do that for every call to the BABYLON namespace.
So I could make a wrapper, for example a BABYLON.wrap.js file :
import {Matrix} from '@babylonjs/core'
export module BABYLON {
Matrix : Matrix
}
then :
import {BABYLON} from './BABYLON.wrap'
let identity = BABYLON.Matrix.Identity();
And again with the external option I’m not including the wrapper in the UMD build. So it could be a solution even if I don’t like it, the main problem with this approach is typescript, there are a tons of errors and I have to put a lot of @ts-ignore. Maybe it will be better with typescript 4.0 but I would like to know if someone already facing this, and what they found to resolve it ?