How Jotai Code Organizes Dev-Only Code

Understand Dead Code Elimination

Hi,

Jotai’s library code includes some logic that is meant to run only in development mode. The same approach applies to Zustand and Valtio, but today let’s take a look at one example from Jotai:

if (import.meta.env?.MODE !== 'production' && !atom) {
  throw new Error('Atom is undefined or null')
}

How Dead Code Elimination Works

In production mode, we expect import.meta.env?.MODE to become 'production'. So this condition effectively turns into:

if ('production' !== 'production' && !atom) {
  throw new Error('Atom is undefined or null')
}

Since this condition is always false, most bundlers will recognize it as dead code and eliminate it during the build process.

Testing With Terser

Let’s try this using Terser REPL.

Input:

export function f() {
  const atom = createAtom();
  if ('production' !== 'production' && !atom) {
    throw new Error('Atom is undefined or null')
  }
}

Output:

export function f(){createAtom()}

As you can see, the conditional block is completely removed.

Taking It Further

We can even move the condition into a utility function:

Input:

function devOnlyThrow(message) {
  if ('production' !== 'production') {
    throw new Error(message)
  }
}

export function f() {
  const atom = createAtom();
  if (!atom) {
    devOnlyThrow('Atom is undefined or null')
  }
}

Output:

export function f(){createAtom()}

This pattern allows you to keep dev-only checks and keep your production bundle clean. You can define utility functions like devOnlyThrow to make development errors more readable without impacting production size.

One Remaining Question

My question is whether other bundlers that don’t use Terser behave the same way. If you’ve tested this in other environments, I’d be curious to hear the results.

Happy coding.

Reply

or to participate.