DEV Community

Cover image for Stop copying your process.env.NODE_ENV to local variables! 🤯
Luciano Graziani
Luciano Graziani

Posted on

Stop copying your process.env.NODE_ENV to local variables! 🤯

Cover image from
https://www.nationalgeographic.com/photography/proof/2017/06/bird-gallery/

TL;DR

Instead of this:

  • Example nº 1:
const localAndLessCode = process.env.NODE_ENV;

if (localAndLessCode !== 'production') {
  // do dev-only things

  console.warn('[dev-only] Warnings to help devs!');
}

export function anotherFunc(num) {
  if (localAndLessCode !== 'production' && typeof num !== 'number') {
    console.warn('[dev-only] Warnings to help devs!');
  }

  // Do something
}

Do the following:

  • Example nº 2:
if (process.env.NODE_ENV !== 'production') {
  // do dev-only things

  console.warn('[dev-only] Warnings to help devs!');
}

export function anotherFunc(num) {
  if (process.env.NODE_ENV !== 'production' && typeof num !== 'number') {
    console.warn('[dev-only] Warnings to help devs!');
  }

  // Do something
}

Why?

Tools like babel will replace every process.env.NODE_ENV (and any other proces.env variable) with its value. Then, the examples above would be transformed like this:

  • Example nº 1 transformed:
const localAndLessCode = 'production';

if (localAndLessCode !== 'production') {
  // do dev-only things

  console.warn('[dev-only] Warnings to help devs!');
}

export function anotherFunc(num) {
  if (localAndLessCode !== 'production' && typeof num !== 'number') {
    console.warn('[dev-only] Warnings to help devs!');
  }

  // Do something
}
  • Example nº 2 transformed:
if ('production' !== 'production') {
  // do dev-only things

  console.warn('[dev-only] Warnings to help devs!');
}

export function anotherFunc(num) {
  if ('production' !== 'production' && typeof num !== 'number') {
    console.warn('[dev-only] Warnings to help devs!');
  }

  // Do something
}

As you can see, in the second example, both comparisons are static. This is something that uglifiers like the webpack's TerserPlugin or babel-minify will take as advantage to literally remove those ifs (and their content!).

It's free!

This is really cool because you don't have to configure anything to reduce your bundle size, it's something you can fix in your code! And it will help you reduce a lot of code you don't want to have in production builds!

Oldest comments (2)

Collapse
 
naismith profile image
Chris Naismith

Yes using tools like babel will do the replacement. But from readability - it's much easier to assign it to a variable and continue to use that variable. Assigning it to a variable also allows for defaults if something is not set, like a port number being defaulted to 3000.

Collapse
 
lgraziani2712 profile image
Luciano Graziani • Edited

That's true if you know you're going to keep using that variable (and the code around it) in your production code.