FORSMILE
JA
JavaScript2020/07/31

[JavaScript] Setting Environment Variables with Webpack and dotenv

dotenv is a Node.js module that allows you to configure variables that change depending on the environment, such as dev/stg/prod.

Back to Blog

dotenv is a Node.js module that allows you to configure variables that change depending on the environment, such as dev/stg/prod.

HOW TO USE DOTENV-WEBPACK

To use it with Webpack, install the following module.

Installation

bash
npm install dotenv-webpack --save-dev

Creating a .env File

Place the created .env file in the same directory as webpack.config.js.

It is also possible to specify the file path when configuring dotenv.

text
// .env
DB_HOST=127.0.0.1
DB_PASS=foobar
S3_API=mysecretkey

Configuring the Config File

javascript
// webpack.config.js
const Dotenv = require('dotenv-webpack');
 
module.exports = {
  ...
  plugins: [
    new Dotenv()
  ]
  ...
};

Calling the Configured Variables

You can call them as shown below within the JavaScript bundled by Webpack.

text
console.log(process.env.DB_HOST);

USING DOTENV-CONFIGURED VARIABLES IN WEBPACK.CONFIG.JS

Since dotenv-webpack is configured as a plugin during bundling, you cannot access the configured variables directly within webpack.config.js.

To use them within webpack.config.js, call dotenv as follows.

text
require('dotenv').config();

Since dotenv-webpack wraps dotenv, you can use it without reinstalling dotenv.

Furthermore, if you only plan to use it within webpack.config.js, installing just dotenv instead of dotenv-webpack is sufficient.

Using .env files instead of environment variables (dotenv)

EXCLUDE FROM GIT MANAGEMENT AS IT OFTEN CONTAINS SENSITIVE INFORMATION

Make sure to add .env files to your .gitignore.

RECOMMENDED JAVASCRIPT BOOKS

There's a lot of information about JavaScript online, and Google search is very convenient, so you might not feel the need to read books.

However, if you're just starting, reading a simple book might deepen your understanding. While there are good reference books, Google search is often more convenient for copying and pasting code, so you might not need them.

Enlightenment! JavaScript – Understanding the Essence of JavaScript from Language Specifications

Highly recommended! You can learn JavaScript concepts that don't easily appear in Google searches. After finishing this, I felt my coding skills had significantly improved.

📦
Amazon で関連書籍・ツールを検索
JavaScript programming book
Amazonで探す →(アソシエイトリンク)