Node.js module support

In the past few weeks I’ve explored the possibilities of making Web games with Cocos Creator. The games need to integrate with our current tech stack which includes several NPM packages. I was hopeful reading that Cocos Creator 3 supported NPM out of the box. Alas, the hope has dwindled as I dug further.

Several of our NPM dependencies are dependent on the Node.js API. Which Cocos Creator 3 doesn’t support judging by documentation, forum posts and hours of error solving attempts. Not even this tutorial and linked use case have managed to solve my issues.

Integrating Cocos Creator 3.2.0 has been fruitless so far. However, it does seem to work with Cocos Creator 2.4.6! One such NPM package is styled-components. Importing anything with a reference to styled-components in 3.2.0 results in a “Failed to resolve stream from…” error. Which is similar to the problems regarding socket-io-client. Applying the suggested fix of importing a browser version of styled-components does resolve stream but immediately causes more errors. Mainly “ReferenceError: process is not defined” during runtime. However, none of these Node.js issues exists with Cocos Creator 2.4.6. It just eats up the dependencies and the game plays fine.

The lack of Node.js support in Cocos Creator 3 severely limits the engines usefulness. And it seems like I’m not the first one hitting this limitation. At this point I consider giving up on Cocos Creator. Which is a shame because I’m otherwise super impressed with Cocos Creator’s editor and features. But before I give up, I have a couple of questions.

  1. Why can’t Cocos Creator 3 consume Node.js modules when Cocos Creator 2 can?

  2. Are there plans to add Node.js module support to Cocos Creator 3 for web games?

  3. If not, what is the recommended way to use Node.js module dependent packages with Cocos Creator games?

I hope you can bring some clarity to my conundrum and possibly a way forward with what is otherwise an excellent game engine.

1 Like

Use this

import io from "socket.io-client/dist/socket.io.js";

Then create a file xxx.d.ts and add this code below to it.

declare module "socket.io-client/dist/socket.io.js" {
    import io from "socket.io-client";
    export default io;
}

You can use this trick for all npm modules you want.

As I mentioned in my initial post. I’ve already tried that socket-io solution. It doesn’t work with the npm packages I need to use (e.g. styled-components). I only leads to run time errors. I don’t have this issue with Cocos Creator 2.4.6. Can you please provide information to why the Node.js module support is worse in Cocos Creator 3 @laminhtruong?