DEV Community

Cover image for Adding Environment Variables to Your Webpack Project
Jake Hayes
Jake Hayes

Posted on • Originally published at jakehayes.net on

Adding Environment Variables to Your Webpack Project

Adding environment variables to your Webpack project is simple and easy. All you need to do is add dotenv-webpack into the dev dependencies in your package.json

pnpm i -D dotenv-webpack

Enter fullscreen mode Exit fullscreen mode

Then in the webpack.config.js, add this to the plugins:

{
 plugins: [
   new Dotenv({
  path: `./.env.${process.env.NODE_ENV}`,
   }),
 ],
};

Enter fullscreen mode Exit fullscreen mode

With this setup, it will be easiest to set the NODE_ENV as part of your scripts in your package.json

{
 "scripts": {
  "dev": "NODE_ENV=local ...",
  "build": "NODE_ENV=release ...",
  // ...
 },
 // ...
}

Enter fullscreen mode Exit fullscreen mode

Then you can create files based on the path provided ./.env.local and ./.env.release (you'll need to match yours up with whatever path and file name you specify in Webpack). Then the .env files are formatted the same as you would in any other project:

KEY=VALUE

Enter fullscreen mode Exit fullscreen mode

Then in javascript all you need to access the value is to look at the process.env object like this:

const value = process.env.KEY;

Enter fullscreen mode Exit fullscreen mode

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs