Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the point of envifying client side libraries?

In an attempt to address the problem behind a warning coming from Redux I stumbled across the advice which explains that envifying is a necessary step when using React or Redux in order to produce a build that is optimized for production use. Envifying is explained as the process of substituting node specific environment variables such as process.env.NODE_ENV with actual values such as 'production'.

Accepting that envifying is necessary and that the above explanation is true, it confuses me since it seems to assume that client side libraries such as React and Redux would contain node specific environment variables. Yeah I know these libraries in particular are popular for building Isomorphic/Universal JavaScript applications but would find is surprising. I'm I understanding this correctly? If so is there an explanation of the pattern that I need to be aware of where process.env.NODE_ENV is used outside of node?

If I understand the advice properly it would suggest that if I'm using Webpack that I may want to use a plugin such as DefinePlugin like so.

  new webpack.DefinePlugin({
    "process.env.NODE_ENV": process.env.NODE_ENV,
  }),

Which would appear to also require that I set the NODE_ENV variable to the target environment of which build I want to produce for my client side code. This is doubly strange because I'm setting an environment variable on the build server to reflect what the environment should be where the actual code is run on the server it is deployed to.

All this makes me feel like I'm missing something in terms of a general pattern.

Related information:

  • https://github.com/reactjs/redux/issues/1029
  • https://github.com/reactjs/redux/issues/1298
like image 490
jpierson Avatar asked Sep 25 '22 05:09

jpierson


1 Answers

You can have production and development builds / conditions for web apps too! As you mentioned, many isomorphic JS frameworks make use of it.

envify serves to help out in two primary ways for code that uses process.env

  1. Remove any need for shims to support it- Browserify has an automated one clocking in at about ~2kb, and that can matter.
  2. Minify code better- when code becomes something like if ("development" === "production") a good minifier can strip it out completely

Remember that Webpack is all about transforming your (in general, client-side) code. Adding something to essentially find-replace all instances of process.env is well within its use case, and lets you create environment-based behaviors without introducing a new API. Setting its value in your webpack.config is really no different from setting an environment variable on your operating system.

like image 123
Jack Guy Avatar answered Oct 16 '22 10:10

Jack Guy