Cocos Creator v3.0 and NPM Modules

rxjs does not work as normal npm, simply because it has a problem with package.json and does not support running on the native ESM module system. See ESM version is never used · Issue #6321 · ReactiveX/rxjs (github.com) for more details.

The following is a solution for using rxjs in Creator:

  • Principle: use Import maps feature of Creator (supported in v3.3) to map rxjs directly to rxjs.umd.js, skipping the package.json of rxjs.

  • Create a new import-map.json file in the project root directory with the following contents:

    {
        "imports": {
            "rxjs": "./node_modules/rxjs/dist/bundles/rxjs.umd.js"
        }
    }
    
  • Then return to the editor, click Project → Project Settings → Scripting in the top menu bar, and then specify the import-map.json file you just created in the Import maps option.

  • Restart the editor (it needs to be restarted after setting Import maps. Live updates are not yet available).

  • Used in this way:

    import rxjs from 'rxjs';
    const { Observable } = rxjs;
    

For more information about Import maps, please refer to the documentation Import Maps (experimental).

3 Likes