-1

Let's say I have 2 files which are .env.development and .env.production.

In my package.json, since the mode is development, it should access .env.development for the variables.

  "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",
    }),
  ],
};

So that in the frontend, when I use process.env, it will access the variable in .env.development.

Is there any way to do it?

Lin Du
  • 88,126
  • 95
  • 281
  • 483
CCCC
  • 5,665
  • 4
  • 41
  • 88

1 Answers1

0

You can set the system environment variable NODE_ENV at the beginning of the npm script. Use this environment variable to control the built environment.

E.g.

package.json:

"scripts": {
  "build:dev": "webpack",
  "build": "NODE_ENV=production webpack",
  "dev": "webpack serve"
}

webpack.config.js:

const path = require("path");
const Dotenv = require("dotenv-webpack");

const mode =
  process.env.NODE_ENV === "production" ? "production" : "development";

console.log("mode: ", mode);

module.exports = {
  mode,
  entry: path.resolve(__dirname, "./src/index.jsx"),
  devtool: "source-map",
  output: {
    path: path.join(__dirname, "./dist"),
    clean: true,
  },
  devServer: {
    port: 3000,
    static: true,
    historyApiFallback: true,
    open: true,
  },
  plugins: [
    new Dotenv({
      path: path.resolve(__dirname, `./.env.${mode}`),
    }),
  ],
};

.env.development:

PWD=123456

.env.production:

PWD=a)d4125z

For development build npm run build:dev, the output of ./dist/main.js:

/******/ (() => { // webpackBootstrap
var __webpack_exports__ = {};
/*!***********************!*\
  !*** ./src/index.jsx ***!
  \***********************/
console.log("PWD: ", "123456");

/******/ })()
;
//# sourceMappingURL=main.js.map

For production build npm run build, the output:

console.log("PWD: ","a)d4125z");
//# sourceMappingURL=main.js.map
Lin Du
  • 88,126
  • 95
  • 281
  • 483