Search code examples
javascripttypescriptbabylonjsstenciljs

Stencil JS not working with non-default imports


I'm using BabylonJS in a StencilJS app, and I can only seem to import in a very specific way.

For instance I can't do:

import { Engine, Scene } from "babylonjs";

It says 'Engine' is not exported by node_modules\babylonjs\babylon.js But it is..

I can do:

import BABYLON from 'babylonjs';

and use it like

private _scene: BABYLON.Scene;

I'd like for the former to work. Any advice?

The first way is how most tutorials do it, and I refuse to believe SencilJS is just not capable of that. I must be missing something


Solution

  • BabylonJS is provided in two versions (ES5 and ES6). The issue you are referring to is related to ES5 version of package.

    If you do smth like this in your code

    import * as babylon from 'babylonjs';
    console.log(babylon);
    

    and look into the console, you will see next:

    {default: Module, __moduleExports: Module, babylonjs: undefined}

    That's why decomposition is not working, it's not an object that can be serialized the way you expect.

    In documentation they say

    import { Engine, Scene } from 'babylonjs';

    NOTE: if you can't make this import method to work, go to the section on typescript and webpack below.

    However, I failed to make it work for ES5 version. The correct way, as to me would be to use ES6 version of package, which can be installed as

    npm install -S @babylonjs/core
    

    This version allows you to use ES6 packages together with tree shaking and other useful features.

    Your module import, in this case, would look exactly as you wish:

    import {Engine, HemisphericLight, Mesh, Scene} from '@babylonjs/core';
    

    Here is a small example I've done to prove my words.

    Please, let me know if I got you wrong and you expected to have smth different or you need some additional explanations or materials - I'll be happy to assist.