# 八.区分不同环境

# 1.安装

package.json

{
  "name": "8.disEnv",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "webpack-dev-server --open --mode development",
    "build": "webpack"
  },
  "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",
    "webpack-merge": "^4.2.1"
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

# 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.配置

# 3.1 webpack.base.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

# 3.2 webpack.dev.js

let { smart } = require("webpack-merge")
let base = require("./webpack.base.js")

module.exports = smart(base, {
  mode: "development",
  optimization: {
    minimizer: [],
  },
  plugins: [],
})
1
2
3
4
5
6
7
8
9
10

# 3.3 webpack.prod.js

let { smart } = require("webpack-merge");
let base = require("./webpack.base.js");

module.exports = smart(base, {
  mode: "production"
    optimization: {
      minimizer: []
    },
    plugins: []
});
1
2
3
4
5
6
7
8
9
10

# 4.运行

# 4.1 开发环境打包

npm run build -- config webpack.dev.js
1

# 4.2 生产环境打包

npm run build -- config webpack.prod.js
1