Environment Variables

How to tame the devDependencies of your project?

Sometimes a part of your code should execute only during development. Or you could have experimental features in your build that are not ready for production yet. Controlling environment variables becomes valuable as you can toggle functionality using them.

Since JavaScript minifiers can remove dead code (if (false)), you can build on top of this idea and write code that gets transformed into this form. Webpack's DefinePlugin enables replacing free variables so that you can convert

if (process.env.NODE_ENV === "development") {
  console.log("Hello during development");
}

kind of code to if (true) or if (false) depending on the environment.

You can find packages that rely on this behavior. React is perhaps the most known example of an early adopter of the technique. Using DefinePlugin can bring down the size of your React production build somewhat as a result, and you can see a similar effect with other packages as well.

Starting from webpack 4, process.env.NODE_ENV is set within the build based on the given mode but not globally. To pass the variable to other tools, you'll have to set it explicitly outside of webpack or within webpack configuration.

`webpack.EnvironmentPlugin(["NODE_ENV"])` is a shortcut that allows you to refer to environment variables. It uses `DefinePlugin` underneath, and you can achieve the same effect by passing `process.env.NODE_ENV`.
[dotenv-webpack](https://www.npmjs.com/package/dotenv-webpack) goes a step further and maps environment variables from a dotfile (`.env`) to a build using `DefinePlugin` underneath.

The basic idea of DefinePlugin#

To understand the idea of DefinePlugin better, consider the example below:

var foo;
if (foo === "bar") console.log("bar"); // Not free
if (bar === "bar") console.log("bar"); // Free

If you replaced bar with a string like "foobar", then you would end up with the code as below:

var foo;
if (foo === "bar") console.log("bar"); // Not free
if ("foobar" === "bar") console.log("bar");

Further analysis shows that "foobar" === "bar" equals false so a minifier gives the following:

var foo;
if (foo === "bar") console.log("bar"); // Not free
if (false) console.log("bar");

A minifier eliminates the if statement as it has become dead code:

var foo;
if (foo === "bar") console.log("bar"); // Not free
// if (false) means the block can be dropped entirely

Elimination is the core idea of DefinePlugin and it allows toggling. A minifier performs analysis and toggles entire portions of the code.

[babel-plugin-transform-define](https://www.npmjs.com/package/babel-plugin-transform-define) achieves similar behavior with Babel.

Setting process.env.NODE_ENV#

As before, encapsulate this idea to a function. Due to the way webpack replaces the free variable, you should push it through JSON.stringify. You end up with a string like '"demo"' and then webpack inserts that into the slots it finds:

webpack.parts.js

exports.setFreeVariable = (key, value) => {
  const env = {};
  env[key] = JSON.stringify(value);

  return {
    plugins: [new webpack.DefinePlugin(env)],
  };
};

Connect this with the configuration:

webpack.config.js

const commonConfig = merge([
  ...
parts.setFreeVariable("HELLO", "hello from config"),
]);

Finally, add something to replace:

src/component.js

export default (text = "Hello world") => {
export default (text = HELLO) => {
const element = document.createElement("div"); ... };

If you run the application, you should see a new message on the button.

Choosing which module to use#

The techniques discussed in this chapter can be used to choose entire modules depending on the environment. As seen above, DefinePlugin based splitting allows you to choose which branch of code to use and which to discard. This idea can be used to implement branching on module level. Consider the file structure below:

.
└── store
    ├── index.js
    ├── store.dev.js
    └── store.prod.js

The idea is that you choose either dev or prod version of the store depending on the environment. It's that index.js which does the hard work:

if (process.env.NODE_ENV === "production") {
  module.exports = require("./store.prod");
} else {
  module.exports = require("./store.dev");
}

Webpack can pick the right code based on the DefinePlugin declaration and this code. You have to use CommonJS module definition style here as ES2015 imports don't allow dynamic behavior by design.

A related technique, **aliasing**, is discussed in the _Consuming Packages_ chapter.
You have to be careful when doing a check against `process.env.NODE_ENV` in complex pieces of code. [Johnny Reilly gives a good example of a problematic case](https://blog.johnnyreilly.com/2018/03/its-not-dead-webpack-and-dead-code.html).

Conclusion#

Setting environment variables is a technique that allows you to control which paths of the source are included in the build.

To recap:

  • Webpack allows you to set environment variables through DefinePlugin and EnvironmentPlugin. Latter maps the system level environment variables to the source.
  • DefinePlugin operates based on free variables and it replaces them as webpack analyzes the source code. You can achieve similar results by using Babel plugins.
  • Given minifiers eliminate dead code, using the plugins allows you to remove the code from the resulting build.
  • The plugins enable module level patterns. By implementing a wrapper, you can choose which file webpack includes to the resulting build.
  • In addition to these plugins, you can find other optimization related plugins that allow you to control the build result in many ways.

To ensure the build has good cache invalidation behavior, you'll learn to include hashes to the generated filenames in the next chapter. This way the client notices if assets have changed and can fetch the updated versions.

Previous chapter
Tree Shaking

This book is available through Leanpub (digital), Amazon (paperback), and Kindle (digital). By purchasing the book you support the development of further content. A part of profit (~30%) goes to Tobias Koppers, the author of webpack.

Need help?