Using RecastJS on NodeJS or Browser in ESM or CJS

Hello !

I (once again) lost a few hours trying to understand why RecastJS wouldn’t load in an Angular app (v19).
I got the following error message:

Cannot set properties of undefined (setting 'Recast')

I finally found the solution and wanted to share it :blush:
To use Recast anywhere, you need to patch it.

The usage is always the same (ESM build):

import {RecastJSPlugin} from "@babylonjs/core";
import Recast from 'recast-detour';
...
const plugin: RecastJSPlugin = new RecastJSPlugin(await Recast());

But we need to patch 2 files :

  • recast.js
  • recast.es6.js

And replace this["Recast"] = Module; with globalThis["Recast"] = Module;

Until the library is updated, you can use patch-package, just modify the files, create a patch, and apply it using a postinstall script.

Hope this helps!
Y.

1 Like

alternatively, if you’re using vite, adding a plugin like this should do it

{
        name: "fix-recast",
        transform(code, id) {
          if (id.includes("recast-detour.js") || id.includes("recast.es6.js")) {
            return code.replace(`this["Recast"]`, 'window["Recast"]'); // or globalThis["Recast"]
          }
        },
      },
2 Likes