Home > Net >  process.env returns undefined when using .env.development instead of .env
process.env returns undefined when using .env.development instead of .env

Time:11-24

I am using Webpack for development.

When I run the project using .env file, it works as expected.

But when I change it filename to .env.development, the process.env become undefined.

How can I fix it?

package.json

  "scripts": {
    "start": "webpack-dev-server --config ./webpack.config.js"

webpack.config.js

const webpack = require("webpack");
const path = require("path");

const HtmlWebpackPlugin = require("html-webpack-plugin");
const Dotenv = require("dotenv-webpack");

module.exports = {
  mode: "development",
  entry: path.resolve(__dirname, "./src/index.jsx"),
  devtool: "source-map",
  output: {
    path: path.join(__dirname, "/dist"),
    filename: "bundle.js",
  },
  devServer: {
    port: 3000,
    static: true,
    historyApiFallback: true,
    open: true,
  },
  resolve: {...},
  module: {...},
  plugins: [
    new Dotenv(),
    new HtmlWebpackPlugin({
      template: "public/index.html",
      filename: "index.html",
      favicon: "public/favicon.ico",
    }),
    new webpack.ProvidePlugin({
      Buffer: ["buffer", "Buffer"],
    }),
    new webpack.ProvidePlugin({
      process: "process/browser",
    }),
  ],
};

CodePudding user response:

dotenv by default only looks for a .env file. This is deliberate, as an env file should be local only and specific for the environment the app is running in. You shouldn't be keeping around different versions of the env for different environments.

I'll quote from dotenv's docs:

Should I have multiple .env files?

No. We strongly recommend against having a "main" .env file and an "environment" .env file like .env.test. Your config should vary between deploys, and you should not be sharing values between environments.

In a twelve-factor app, env vars are granular controls, each fully orthogonal to other env vars. They are never grouped together as “environments”, but instead are independently managed for each deploy. This is a model that scales up smoothly as the app naturally expands into more deploys over its lifetime.

The Twelve-Factor App

You can however, tell dotenv-webpack where to look for your file if you choose:

  plugins: [
    new Dotenv({
        path: './.env.development',
    }),

  • Related