A preface

References to this article are from juejin.cn/post/684490… , some contents have been modified after testing.

Test system: The relevant code test environment in this article is macOS (2021-08-06)

In daily front-end development work, there are usually two sets of build environment, development environment and production environment.

Webpack provides a mode configuration option that tells WebPack to use the built-in optimizations for the appropriate mode. If not, WebPack will set mode to production by default.

options describe
development willDefinePlugin 中 process.env.NODE_ENVIs set todevelopment. Enable valid names for modules and chunks.
production willDefinePlugin 中 process.env.NODE_ENVIs set toproduction. Enable deterministic obfuscated names for modules and chunks,FlagDependencyUsagePlugin.FlagIncludedChunksPlugin.ModuleConcatenationPlugin.NoEmitOnErrorsPlugin 和 TerserPlugin 。
none Do not use any default tuning options

Ii Multiple ways to configure environment variables

1. Run the cli

Writing a
  • webpack 4
"scripts": {
    "dev": "webpack-dev-server"."build": "webpack"
  },
Copy the code
  • webpack 5
"scripts": {
    "dev": "webpack server"."build": "webpack"
  },
Copy the code
  • The preceding script can be used to obtain the current environment variable from process.env.node_env in any module
  • However, the current environment variable cannot be obtained in the Node environment (in the Webpack configuration file)

webpconk.config.js

const path = require("path"); const HtmlWebpackPlugin = require("html-webpack-plugin"); const { CleanWebpackPlugin } = require("clean-webpack-plugin"); Console. log(' webpack prints process.env.node_env: ${process.env.node_env}\n '); // webpack prints process.env.node_env: undefined module.exports = {entry: {index: "./ SRC /index.js",}, output: {path: path.resolve(__dirname, "./build"), filename: "[name].js", }, ... };Copy the code

src/index.js

console.log(` index printing process. The env. NODE_ENV:${process.env.NODE_ENV}\n`)
// yarn dev
// webpack4 index prints process.env.node_env: development
// webpack5 index prints process.env.node_env: production

// yarn build
// webpack4 index prints process.env.node_env: production
// webpack5 index prints process.env.node_env: production
Copy the code
Write two
  • webpack4
"scripts": {
    "dev2": "webpack-dev-server --mode=development"."build2": "webpack --mode=production"
  },
Copy the code
  • webpack5
"scripts": {
    "dev2": "webpack server --mode=development"."build2": "webpack --mode=production"
  },
Copy the code
  • In the preceding script, you can obtain the current environment variable from process.env.node_env in any module, following the command line--modeThe value of the option
  • However, the current environment variable cannot be obtained in the Node environment (in the Webpack configuration file)
Write three

webpack4

"scripts": {
    "dev3": "webpack-dev-server --env=development"."build3": "webpack --env=production"
  },
Copy the code

webpack5

"scripts": {
    "dev3": "webpack server --env=development"."build3": "webpack --env=production"
  },
Copy the code
  • In development mode (Web server), use process.env.node_env to get the current environment variable.--envWhether you set up development or production,webpack4Always returndevelopment.webpack5Always returnproduction
  • You can get the current environment variable from a function under the Node environment (in the Webpack configuration file)

webpack.config.js

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");

module.exports = (env) = > {
  console.log('Webpack prints env:', env);
  // yarn dev3 --env=development
  // WebPack4 WebPack prints env: development
  // webpack5 webpack 打印 env:  { WEBPACK_SERVE: true, development: true }
  
  // yarn dev3 --env=production
  // Webpack4 Webpack prints env: production
  // webpack5 webpack 打印 env:  { WEBPACK_SERVE: true, production: true }
  
  // yarn build3 --env=development
  // WebPack4 WebPack prints env: development
  // webpack5 webpack 打印 env:  { WEBPACK_BUNDLE: true, WEBPACK_BUILD: true, development: true }
  
  // yarn build3 --env=production
  // Webpack4 Webpack prints env: production
  // webpack5 webpack 打印 env:  { WEBPACK_BUNDLE: true, WEBPACK_BUILD: true, production: true }
  
  return {
    entry: {
      index: "./src/index.js",},output: {
      path: path.resolve(__dirname, "./build"),
      filename: "[name].js",},... }; };Copy the code

src/index.js

console.log(` index printing process. The env. NODE_ENV:${process.env.NODE_ENV}\n`)
// yarn dev --env=development
// webpack4 index prints process.env.node_env: development
// webpack5 index prints process.env.node_env: production

// yarn dev3 --env=production
// webpack4 index prints process.env.node_env: development
// webpack5 index prints process.env.node_env: production

// yarn build3 --env=development --env=production
// webpack4 index prints process.env.node_env: production
// webpack5 index prints process.env.node_env: production
Copy the code

2. Configure options using Webpack Mode

  • The result is the same as using command 2 (–mode)
  • You can get the current environment variable from any module by process.env.node_env, followmodeConfiguration options
  • However, the current environment variable cannot be obtained in the Node environment (in the Webpack configuration file)

webpack.config.js

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");

console.log(` webpack printing process. The env. NODE_ENV:${process.env.NODE_ENV}\n`);
// Webpack prints process.env.node_env: undefined

module.exports = {
  mode: "development".entry: {
    index: "./src/index.js",},output: {
    path: path.resolve(__dirname, "./build"),
    filename: "[name].js",},... };Copy the code

src/index.js

console.log(` index printing process. The env. NODE_ENV:${process.env.NODE_ENV}\n`)
// mode: "development"
// index prints process.env.node_env: development

// mode: "production"
// index prints process.env.node_env: production
Copy the code

3. Use webpack. DefinePlugin

The DefinePlugin allows you to replace variables in your code with other values or expressions at compile time.

  • The current environment variable can be obtained from any module by process.env.node_env
  • However, the current environment variable cannot be obtained in the Node environment (in the Webpack configuration file)

webpack.config.js

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const webpack = require("webpack");

console.log(` webpack printing process. The env. NODE_ENV:${process.env.NODE_ENV}\n`); 
// Webpack prints process.env.node_env: undefined

console.log(` webpack V_VERSION printing:${V_VERSION}`);
// ReferenceError: V_VERSION is not defined

module.exports = {
  entry: {
    index: "./src/index.js",},output: {
    path: path.resolve(__dirname, "./build"),
    filename: "[name].js",},devServer: {
    contentBase: path.join(__dirname, "dist"),
    compress: false.port: 8000,},/ / the plugin
  plugins: [
    new webpack.DefinePlugin({
      "process.env.NODE_ENV": JSON.stringify("development"),
      V_VERSION: JSON.stringify("v1.0.0"),}),new CleanWebpackPlugin(),
    new HtmlWebpackPlugin({
      // Template matching
      template: "./src/index.html".filename: "index.html".chunks: ["index"],}),]};Copy the code

src/index.js

console.log(` index printing process. The env. NODE_ENV:${process.env.NODE_ENV}\n`)
// index prints process.env.node_env: development

console.log(` index print V_VERSION:${V_VERSION}`)
// index prints V_VERSION: v1.0.0
Copy the code

4. Use the cross-env plug-in

Writing a

webpack4

"scripts": {
    "dev4": "Cross - the env NODE_ENV = development V_VERSION = v2.0.0 webpack dev - server"."build4": "Cross - the env NODE_ENV = production V_VERSION = v2.0.0 webpack"
  },
Copy the code

webpack5

"scripts": {
    "dev4": "cross-env NODE_ENV=development V_VERSION='v2.0.0' webpack server"."build4": "Cross - the env NODE_ENV = production V_VERSION = v2.0.0 webpack"
  },
Copy the code
  • The current environment variable can be obtained from process.env.NODE_ENV in any module. The value of NODE_ENV on the command line is either development or production.webpack4In development mode (Web Server), the values are bothdevelopment, the production build time value isproduction.webpack5The value of the environment variable follows the value of the NODE_ENV command line
  • You can get the current environment variable in the Node environment (in the Webpack configuration file), following the value of the command line NODE_ENV

webpack.config.js

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");

console.log(` webpack printing process. The env. NODE_ENV:${process.env.NODE_ENV}\n`);
// yarn dev4 NODE_ENV=development
// Webpack prints process.env.node_env: development

// yarn dev4 NODE_ENV=production
// Webpack prints process.env.node_env: production

// yarn build4 NODE_ENV=development
// Webpack prints process.env.node_env: development

// yarn build4 NODE_ENV=production
// Webpack prints process.env.node_env: production

console.log(` webpack V_VERSION printing:${V_VERSION}`);
// ReferenceError: V_VERSION is not defined

module.exports = {
  entry: {
    index: "./src/index.js",},output: {
    path: path.resolve(__dirname, "./build"),
    filename: "[name].js",},devServer: {
    contentBase: path.join(__dirname, "dist"),
    compress: false.port: 8000,},... };Copy the code

src/index.js

console.log(` index printing process. The env. NODE_ENV:${process.env.NODE_ENV}\n`)
// yarn dev4 NODE_ENV=development
// webpack4 index prints process.env.node_env: development
// webpack5 index Prints process.env.node_env: development

// yarn dev4 NODE_ENV=production
// webpack4 index prints process.env.node_env: development
// webpack5 index prints process.env.node_env: production

// yarn build4 NODE_ENV=development
// webpack4 index prints process.env.node_env: production
// webpack5 index Prints process.env.node_env: development

// yarn build4 NODE_ENV=production
// webpack4 index prints process.env.node_env: production
// webpack5 index prints process.env.node_env: production


console.log(` index print V_VERSION:${V_VERSION}`)
// Uncaught ReferenceError: V_VERSION is not defined
Copy the code
Write two

webpack4

"scripts": {
    "dev5": "cross-env NODE_ENV=development webpack-dev-server --mode development"."build5": "cross-env NODE_ENV=production webpack --mode production"
  },
Copy the code

webpack5

"scripts": {
    "dev5": "cross-env NODE_ENV=development webpack server --mode development"."build5": "cross-env NODE_ENV=production webpack --mode production"
  },
Copy the code
  • You can get the current environment variable from any module via process.env.node_env, following the command line--modeThe value of the option
  • You can get the current environment variable in the Node environment (in the Webpack configuration file), following the value of the command line NODE_ENV

webpack.config.js

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");

console.log(` webpack printing process. The env. NODE_ENV:${process.env.NODE_ENV}\n`);
// yarn dev5 NODE_ENV=development --mode development
// Webpack prints process.env.node_env: development

// yarn dev5 NODE_ENV=production --mode production
// Webpack prints process.env.node_env: production

// yarn dev5 NODE_ENV=development --mode production
// Webpack prints process.env.node_env: development

// yarn dev5 NODE_ENV=production --mode development
// Webpack prints process.env.node_env: production

// yarn build5 NODE_ENV=development --mode development
// Webpack prints process.env.node_env: development

// yarn build5 NODE_ENV=production --mode production
// Webpack prints process.env.node_env: production

// yarn build5 NODE_ENV=development --mode production
// Webpack prints process.env.node_env: development

// yarn build5 NODE_ENV=production --mode development
// Webpack prints process.env.node_env: production


module.exports = {
  entry: {
    index: "./src/index.js",},output: {
    path: path.resolve(__dirname, "build"),
    filename: "[name].js",},... };Copy the code

src/index.js

console.log(` index printing process. The env. NODE_ENV:${process.env.NODE_ENV}\n`)
// yarn dev5 NODE_ENV=development --mode development
// index prints process.env.node_env: development

// yarn dev5 NODE_ENV=production --mode production
// index prints process.env.node_env: production

// yarn dev5 NODE_ENV=development --mode production
// index prints process.env.node_env: production

// yarn dev5 NODE_ENV=production --mode development
// index prints process.env.node_env: development

// yarn build5 NODE_ENV=development --mode development
// index prints process.env.node_env: development

// yarn build5 NODE_ENV=production --mode production
// index prints process.env.node_env: production

// yarn build5 NODE_ENV=development --mode production
// index prints process.env.node_env: production

// yarn build5 NODE_ENV=production --mode development
// index prints process.env.node_env: development
Copy the code

conclusion

  • cross-env: is a script that runs cross-platform Settings and uses environment variables (environment variables in Node).

  • --mode: You can get the current environment variable in any module by process.env.node_env, but you cannot get the current environment variable in the Node environment (webpack configuration file)

  • DefinePlugin: Allows variables in code to be replaced with other values or expressions at compile time. The current environment variable can be obtained from process.env.node_env in any module, but cannot be obtained from the Node environment (webpack configuration file)