mobxjs / mobx

Simple, scalable state management.
http://mobx.js.org
MIT License
27.6k stars 1.77k forks source link

Uncaught ReferenceError: process is not defined #3809

Open justinfagnani opened 11 months ago

justinfagnani commented 11 months ago

Intended outcome:

The mobx module load in a browser

Actual outcome:

mobx.esm.js throws an error:

Uncaught ReferenceError: process is not defined
    at errors.ts:78:35

How to reproduce the issue:

Use any system that loads modules directly to the browser, such as unpkg.com, jsDelivr, the lit.dev playground, etc.

The import something from mobx, like:

import {makeObservable, observable, action} from 'mobx';

This is due to this line in errors.ts:

var errors = process.env.NODE_ENV !== "production" ? niceErrors : {};

Presumably that comes from this source line:

const errors: typeof niceErrors = __DEV__ ? niceErrors : ({} as any)

but I can't see where __DEV__ is defined.

See this lit.dev playground reproduction:

https://lit.dev/playground/#gist=683ed61114ad2a20430fc8b1cc8229c8

You can get this working by defining window.process.env before loading the main script, but many users do not know to do that and get stuck.

Versions

6.12.0

Potential Solutions

Previous issues (https://github.com/mobxjs/mobx/issues/2564) have been closed due to bundlers using process.env.NODE_ENV !== "production" for optimization. This shouldn't be necessary anymore with wide support for Node package export conditions. Packages can publish separate builds for default and development conditions and tools will pick the correct build.

It's relatively easy to make these separate builds. Packages can define constants (like const __DEV__ = true) that are replaced in the default (prod) build to be false. The a tool like Rollup + Terser can do constant folding and dead code elimination to remove any code gated by if (__DEV__), etc.

urugator commented 11 months ago

Use one of these:

https://github.com/mobxjs/mobx/blob/55260aa158919033e862d219e60eea601a05ac61/scripts/build.js#L56-L59

https://www.unpkg.com/browse/mobx@6.12.0/dist/

package export conditions

I am not up to date how "wide" the support is or what is or isn't possible. If you can guarantee it will work well with various setups, won't break existing uses and provide appropriate documentation, PR welcome.