Use Mobx lib with v3.8.1

Hello,

I’m trying to setup the Mobx state management library inside my project, but not matter how much I try, it does not work correctly with the bundler.

Don’t matter how much I try I can’t get it to run with cocos. I’m trying a very basic example

TypeError: (intermediate value)(intermediate value)(intermediate value) is not a function
at new Todo (file:///D:/gamedev/cocos/projects/FlippyPlane/temp/programming/packer-driver/targets/editor/chunks/5c/file:/D:/gamedev/cocos/projects/FlippyPlane/assets/manager/scripts/state/StateManager.ts:9:9)
import { action, makeObservable, observable } from 'mobx';

export class Todo {
    id = Math.random();
    title = '';
    finished = false;

    constructor(title: string) {
        makeObservable(this, {
            title: observable,
            finished: observable,
            toggle: action,
        });
        this.title = title;
    }

    toggle() {
        this.finished = !this.finished;
    }
}

if I try to set it with mobx/dist/mobx.esm.js, I then get: [Scene] Error: Error: Unexpected export statement in CJS module.

Ok so I’ve spent a bit of time trying to understand the issue here and I might think this could be a bug for the engine/bundle process.

So basically I was able to setup Redux into my project, but the only reason was because the bundle was .mjs file. Currently, most modern exports for esm commons use the extension .ems.js instead of .mjs.

It works by renaming the extension from .ems.js to .mjs, puff.

So it seems that Cocos because of the name convention cannot resolve the module or is not including .ems.js extensions into the resolve path.

For a better solution I’ve found this neat trick

In fact no luck after the build =T

Found one file for Mobx that works

import mobx from 'mobx/dist/mobx.cjs.development.js';
1 Like