# 七.定义环境变量

# 1.安装

package.json

{
  "name": "7.defineEnv",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "webpack-dev-server --open --mode development"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "html-webpack-plugin": "^3.2.0",
    "webpack": "^4.29.6",
    "webpack-cli": "^3.3.0",
    "webpack-dev-server": "^3.2.1"
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

# 2.文件

# 2.1 src/index.js

let url = ""
if (DEV === "dev") {
  url = "http:localhost:3000"
} else {
  url = "http:zhoubichuan.com"
}
console.log(url)
console.log(typeof FLAG)
console.log(EXPORESSION)
1
2
3
4
5
6
7
8
9

# 2.2 index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>webpac定义环境变量</title>
  </head>

  <body></body>
</html>
1
2
3
4
5
6
7
8
9
10
11

# 3.配置

webpack.config.js

const path = require("path")
let HtmlWebpackPlugin = require("html-webpack-plugin")
let webpack = require("webpack")

module.exports = {
  mode: "development",
  entry: {
    home: "./src/index.js",
  },
  output: {
    filename: "[name].js",
    path: path.resolve(__dirname, "dist"),
  },
  plugins: [
    new webpack.DefinePlugin({
      // DEV: "'dev'"
      DEV: JSON.stringify("production"),
      FLAG: "true",
      EXPORESSION: JSON.stringify("1+1"),
    }),
    new HtmlWebpackPlugin({
      template: "./index.html",
      filename: "index.html",
    }),
  ],
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

# 4.运行

npm run dev
1

控制台打印我们所要的信息

http:zhoubichuan.com
boolean
1+1
1
2
3