The problem of setting environment variables with DefinePlugin in webpack

recently, when I was reading the official documents of webpack4, I was confused by one thing, that is, the problem of setting environment variables using DefinePlugin. See Code:

import webpack from "webpack";

// `ASSET_PATH`
const ASSET_PATH = process.env.ASSET_PATH || "/";

export default {
  output: {
    publicPath: ASSET_PATH
  },

  plugins: [
    // 
    new webpack.DefinePlugin({
      "process.env.ASSET_PATH": JSON.stringify(ASSET_PATH)
    })
  ]
};

this is the code on the official website ides/public-path/" rel=" nofollow noreferrer "> this is the link

I would like to ask, above is to assign process.env.ASSET_PATH to ASSET_PATH, and below is to use DefinePlugin to set the value of process.env.ASSET_PATH to aset _ PATH. What does this mean?
there are no great gods, can explain a little easier to understand, thank you!

Dec.06,2021

look at the answer above is speechless.
Webpack is a program that belongs to Node. Webpack can be configured to read environment variables in Node environment.

but index.js belongs to the artifact that Webpack wants to build, if it also wants to read environment variables. You can click on the
index.js through this DefinePlugin and you can read it.


manually typed it again, and the conclusion is that it doesn't make any sense.
execute const ASSET_PATH = process.env.ASSET_PATH first | |'/';
at this time process.env.ASSET_PATH is unknown, so ASSET_PATH ='/';
and then execute

new webpack.DefinePlugin({
  'process.env.ASSET_PATH': JSON.stringify(ASSET_PATH)
})

at this time ASSET_PATH ='/'; is equivalent to

.
new webpack.DefinePlugin({
  'process.env.ASSET_PATH': '/'
})

it's that simple

Menu