BabylonJS and React - ReferenceError: earcut is not defined

Viewed 1123

Working with BabylonJS and React. In my local React environment I am able to create a scene using just a sphere. Moving past that I was able to create a ring made up of segments. The code works well in the playground running the same version (4.1.0) that is used for React as well as the newest alpha-version.

https://www.babylonjs-playground.com/#KECBIZ

When I move this code from the playground into my local React environment I get the following error:

Function.push../node_modules/@babylonjs/core/Meshes/Builders/polygonBuilder.js._mesh__WEBPACK_IMPORTED_MODULE_2__.Mesh.ExtrudePolygon
C:/sourceES6/core/Meshes/Builders/polygonBuilder.ts:85
  82 |     return PolygonBuilder.CreatePolygon(name, options, scene, earcutInjection);
  83 | };
  84 | 
> 85 | Mesh.ExtrudePolygon = (name: string, shape: Vector3[], depth: number, scene: Scene, holes?: Vector3[][], updatable?: boolean, sideOrientation?: number, earcutInjection = earcut): Mesh => {
  86 |     var options = {
  87 |         shape: shape,
  88 |         holes: holes,

Code from my local React environment

    var scene = new BABYLON.Scene(engine);
    var camera = new BABYLON.ArcRotateCamera('Camera', Math.PI / 2, 0, 50, BABYLON.Vector3.Zero(), scene);
    camera.setTarget(BABYLON.Vector3.Zero());
    camera.attachControl(canvas, true);

    var light = new BABYLON.HemisphericLight("light", new BABYLON.Vector3(0, 1, 0), scene);
    light.intensity = 0.7;

    let ring = createRing(10, 2, 2, 16);
    ring.segments.forEach(s => {
        let polygon = BABYLON.Mesh.ExtrudePolygon(ring.id, s.vectors, 2, scene);
        polygon.rotate(BABYLON.Axis.Y, s.offset);
    });

I have installed Earcut using NPM (https://doc.babylonjs.com/how_to/polygonmeshbuilder). What am I missing?

2 Answers

You need to update your webpack plugins:

    plugins: [
        ...
        new webpack.ProvidePlugin({
            'earcut': 'earcut'
        }),
    ]

You can import it in index.tsx file like this without changing webpack

import * as earcut from "earcut";
(window as any).earcut = earcut;

And also you need to do

npm install @types/earcut --save-dev
npm install earcut --save
Related