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

Top comments (0)