How to handle process.env in external npm packages?

Hello,

Many npm packages use process.env variables (process.env.NODE_ENV in particular) and when I include them in my CC project I get the process.env is undefined error.

Is there any way to fix this issue?

There is no env in the Cocos JS environment because we don’t have node.js in the runtime. If it’s hard dependency then the module is not usable, maybe find some alternative

You can eventually use the browser version and include it as plugin it they expose the library at global level. Plugin Scripts · Cocos Creator

It’s a common practice when browser packages that don’t use any nodejs APIs can use process.env. Usually the bundler (webpack, rollup, esbuild etc.) substitutes expressions like process.env.NODE_ENV with constans during the build step.

E.g.

// original code
if (process.env.NODE_ENV === 'production') {...}

// code after bundling
if ('production' === 'production') {...}