Webpack-compliant imports for Cannon.js

Hi Babylonians,

I have a problem that will hopefully be straightforward to solve. For a small project, I need to include cannon.js and the corresponding babylon plugin. For this project I am using webpack from the start. I installed everything through npm and then imported things this way:

import "cannon";
import CannonJSPlugin from "babylonjs";
import "@babylonjs/core/Physics/physicsEngineComponent";

(I am not very sure if that’s correct, probably CannonJSPlugin should also be in the @babylonjs/ tree somewhere, but I can’t find it…)

On the enablePhysics() line I get the following error in the browser console:
TypeError: babylonjs__WEBPACK_IMPORTED_MODULE_14___default.a is not a constructor

I suspect I am missing an import.

I really love the webpack interaction, but the documentation on package paths could definitely be improved (especially if this is in fact what’s causing this).

Thanks in advance!

We normally allow the canon injection in the cannon plugin, you can have a look at:

Thank you for the pointer, but unfortunately that doesn’t seem to make a difference, unless I’m missing something. I added the following lines to my module.exports:

context: __dirname,
plugins: [
  new webpack.ProvidePlugin({
    'cannon': 'cannon'

No difference. Is there anything else I have to change, i.e. import things differently or something? I only ever have used webpack with React, and there it’s very straightforward, therefore I don’t know much about how those plugin injections work.

To me it’s strange that it compiles perfectly but at runtime it’s missing the class.

yup the easiest would be to share your repo on Github so we can have a look ???

There you go:

If you remove line 60 in src/index.js it will run just fine. Only once scene.enablePhysics is called it tries to load a class that is undefined.

It took me a bit longer because I first had to figure out some unrelated webpack stuff before I got the example working :man_facepalming: It’s not the easiest “build system” to learn.

use named import

import { CannonJSPlugin } from "babylonjs";
1 Like

Thank you! This pointed me in the right direction. There was still a different issue to solve (“CANNON” is not defined), but I managed that too.

My next attempt was combining this with the answer from Cannon.js NPM "CANNON is not defined" in v4.0.0-alpha.21 but works in v4.0.0-alpha.16

Now the relevant lines look like this (the code has also been updated on gitlab):

import * as cannon from "cannon";
import { CannonJSPlugin } from "babylonjs"
// ...
scene.enablePhysics(null, new CannonJSPlugin(true, 10, cannon));

I also had to reinstall cannon somehow (npm install --save-dev cannon) or it would complain how it couldn’t find it, but now it works!

Thank you all! I hope this will help someone else in the future.

1 Like