# 六.抽离公共代码

# 1.安装

package.json

{
  "name": "6.commonCode",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "build": "webpack",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.4.0",
    "@babel/preset-env": "^7.4.2",
    "@babel/preset-react": "^7.0.0",
    "babel-loader": "^8.0.5",
    "html-webpack-plugin": "^3.2.0",
    "webpack": "^4.29.6",
    "webpack-cli": "^3.3.0",
    "webpack-dev-server": "^3.2.1"
  },
  "dependencies": {
    "jquery": "^3.3.1",
    "moment": "^2.24.0"
  }
}
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
27

# 2.文件

src/a.js

console.log("a------")
1

src/b.js

console.log("b------")
1

src/c.js

import $ from "jquery"
console.log($)
1
2

src/index.js

import a from "./a.js"
import b from "./b.js"
import $ from "jquery"

console.log(a, b, "index.js")
console.log($)
1
2
3
4
5
6

src/other.js

import a from "./a.js"
import b from "./b.js"
import $ from "jquery"

console.log(a, b, "other.js")
console.log($)
1
2
3
4
5
6

# 3.配置

webpack.config.js

let path = require("path")
let HtmlWebpackPlugin = require("html-webpack-plugin")
let webpack = require("webpack")
module.exports = {
  mode: "production",
  optimization: {
    splitChunks: {
      //分割代码块
      cacheGroups: {
        //缓存组
        //公共的模块
        common: {
          chunks: "initial",
          minSize: 0,
          minChunks: 2,
        },
        vendor: {
          priority: 1,
          test: /node_modules/,
          chunks: "initial",
          minSize: 0,
          minChunks: 2,
        },
      },
    },
  },
  entry: {
    index: "./src/index.js",
    other: "./src/other.js",
  },
  output: {
    filename: "[name].js",
    path: path.resolve(__dirname, "dist"),
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: "./public/index.html",
    }),
    new webpack.IgnorePlugin(/\.\/locale/, /moment/),
  ],
  module: {
    noParse: /jquery/, //不去解析jquery中的依赖库
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        include: path.resolve("src"),
        use: {
          loader: "babel-loader",
          options: {
            presets: ["@babel/preset-env", "@babel/preset-react"],
          },
        },
      },
    ],
  },
}
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57

# 4.打包

npm run build
1

common 公共代码 vendor 第三方库

                Asset       Size  Chunks             Chunk Names
common~index~other.js  137 bytes       0  [emitted]  common~index~other
           index.html  526 bytes          [emitted]
             index.js   1.54 KiB       2  [emitted]  index
             other.js   1.54 KiB       3  [emitted]  other
vendor~index~other.js     85 KiB       1  [emitted]  vendor~index~other
1
2
3
4
5
6

完整代码 (opens new window)