# 二.打包相关配置

# 1.打包 js 文件

# 1.搭建环境

  • 1.新建项目文件夹
mkdir webpack-eg
1
  • 2.进入项目文件夹
cd webpack-eg
1
  • 3.初始化项目
npm init -y
1
  • 4.安装 webpack 依赖包

从 webpack4.0 开始需要同时安装 webpack-cli,打包工具上线后不需要所以为开发依赖

npm i webpack webpack-cli -D
1

# 2.设置配置文件

  • 1.新建 webpack.config.js
const path = require("path")
module.exports = {
  //入口,可以是相对路径
  entry: "./src/index.js",
  //输出的文件夹,只能是绝对路径
  output: {
    path: path.join(__dirname, "dist"),
    //打包后的文件名
    filename: "bundle.js",
  },
}
1
2
3
4
5
6
7
8
9
10
11
  • 2.新建要打包的文件 index.js

新建一个 src 文件夹,下面新建一个 index.js

consoel.log("hello")
1

# 3.运行打包命令

  • 1.第一种方式是通过配置 package.json 中的 script "build"

package.json

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
1
2
3
  • 修改后
"scripts": {
    "build": "webpack --mode development"
  },
1
2
3

从 webpack4.0 开始 webpack 后面需要加 --mode 指定是生产模式(production)还是开发模式(development);

开发模式更加符合开发方式,日志调试等功能更加全面,生产模式更加符合生产要求,加密压缩等功能使代码更安全性能更高。

  • 运行
npm run build
1
  • 2.第二种方式是通过 npx

可以直接运行 node_modules/.bin 目录下的命令

npx webpack
1

# 4.打包后的文件

打包后项目生成一个 dist 文件夹,下面有一个 bundle.js

!(function (e) {
  var t = {}
  function n(r) {
    if (t[r]) return t[r].exports
    var o = (t[r] = { i: r, l: !1, exports: {} })
    return e[r].call(o.exports, o, o.exports, n), (o.l = !0), o.exports
  }
  ;(n.m = e),
    (n.c = t),
    (n.d = function (e, t, r) {
      n.o(e, t) || Object.defineProperty(e, t, { enumerable: !0, get: r })
    }),
    (n.r = function (e) {
      "undefined" != typeof Symbol &&
        Symbol.toStringTag &&
        Object.defineProperty(e, Symbol.toStringTag, { value: "Module" }),
        Object.defineProperty(e, "__esModule", { value: !0 })
    }),
    (n.t = function (e, t) {
      if ((1 & t && (e = n(e)), 8 & t)) return e
      if (4 & t && "object" == typeof e && e && e.__esModule) return e
      var r = Object.create(null)
      if (
        (n.r(r),
        Object.defineProperty(r, "default", { enumerable: !0, value: e }),
        2 & t && "string" != typeof e)
      )
        for (var o in e)
          n.d(
            r,
            o,
            function (t) {
              return e[t]
            }.bind(null, o)
          )
      return r
    }),
    (n.n = function (e) {
      var t =
        e && e.__esModule
          ? function () {
              return e.default
            }
          : function () {
              return e
            }
      return n.d(t, "a", t), t
    }),
    (n.o = function (e, t) {
      return Object.prototype.hasOwnProperty.call(e, t)
    }),
    (n.p = ""),
    n((n.s = 0))
})([
  function (e, t) {
    console.log("hello"), (document.getElementById("app").innerHTML = "123")
  },
])
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
58

完整代码 (opens new window)

# 2.打包 html 文件

# 1.配置

package.json

{
  "name": "eg2",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "build": "webpack --config webpack.config.js",
    "dev": "webpack-dev-server --open --mode development"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "html-webpack-plugin": "^3.2.0",
    "webpack": "^4.28.3",
    "webpack-cli": "^3.1.2",
    "webpack-dev-server": "^3.1.14"
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

src/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>Document</title>
  </head>

  <body>
    <div id="app"></div>
  </body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13

src/index.js

document.getElementById("app").innerHTML = "123"
1

webpack.config.js












 
 
 
 
 
 
 
 
 



const path = require("path")
const HtmlWebpackPlugin = require("html-webpack-plugin")
//开发服务器配置
module.exports = {
  mode: "development",
  entry: "./src/index.js",//入口,可以是相对路径
  output: {
    path: path.resolve(__dirname, "dist"),//输出的文件夹,只能是绝对路径
    filename: "[name].[hash:8].js",//打包后的文件名,name是entry名字,hash根据打包后的文件内容计算出来的一个值
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: "./src/index.html",
      filename: "index.html",
      minify: {
        removeAttributeQuotes: true,
        collapseWhitespace: true,
      },
      hash: true,
    }),
  ],
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

# 2.打包

npm run build
1

# 3.运行

npm run dev
1

完整代码 (opens new window)

# 3.打包 css 文件

less文件--> less-loader --> css文件 --> css-loader --> @import等语法 --> style-loader --> js中页面插入<style>

# 1.配置

package.json

{
  "name": "eg4",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "build": "webpack --config webpack.config.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "css-loader": "^2.1.1",
    "html-webpack-plugin": "^3.2.0",
    "style-loader": "^0.23.1",
    "webpack": "^4.29.6",
    "webpack-cli": "^3.2.3"
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

src/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>Document</title>
  </head>

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

src/index.js

import "./style.css"
1

src/style.css

body {
  background: red;
}
1
2
3

webpack.config.js

const path = require("path")
const HtmlWebpackPlugin = require("html-webpack-plugin")
module.exports = {
  mode: "development",
  entry: "./src/index.js",
  output: {
    path: path.resolve(__dirname, "dist"),
    filename: "[name].[hash:8].js",
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: "./src/index.html",
      filename: "index.html",
      minify: {
        removeAttributeQuotes: true,
        collapseWhitespace: true,
      },
      hash: true,
    }),
  ],
  //模块
  module: {
    //规则 css-loader 解析 @import这种语法
    //loader的特点 希望单一
    //loader的用法 字符串只用一个loader
    //多个loader需要 []
    //loader的顺序 默认是从右向左执行 从下向上执行
    rules: [
      { test: /\.css$/, use: [{ loader: "style-loader" }, "css-loader"] },
    ],
  },
}
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

# 2.打包

npm run build
1

使用 less

src/index.html

<body>
  <div>1111111111111111</div>
</body>
1
2
3

src/index.less

body {
  div {
    border: 1px solid black;
  }
}
1
2
3
4
5

src/index.js

import "./index.less"
1

安装 less、less-loader

npm i less less-loader -D
1

webpack.config.js

{
  "test": /\.less$/,
  "use": [
    {
      "loader": "style-loader",
      "options": {
        "insertAt": "top"
      }
    },
    "css-loader",
    "less-loader"
  ]
}
1
2
3
4
5
6
7
8
9
10
11
12
13

完整代码 (opens new window)

# 4.打包文件分类

# 1.配置

img 打包分类

use: {
    loader: "url-loader",
    options: {
    limit: 1,
    outputPath: "/img/"
    }
}
1
2
3
4
5
6
7

css 打包分类

new MiniCssExtractPlugin({
  filename: "css/main.css",
})
1
2
3

# 2.打包

npm run build
1

dist 目录下有 img 和 css 文件夹

文件前加 cdn 前缀

全部加的配置

output: {
    path: path.resolve(__dirname, "dist"),
    filename: "[name].[hash:8].js",
    publicPath: "http://www.zbc.com"
},
1
2
3
4
5

只加图片

options: {
    limit: 1,
    outputPath: "/img/",
    publicPath: "http://www.zbc.com"
}
1
2
3
4
5

# 3.打包

npm run build
1

发现前者全部加前缀

后者只有图片加前缀

完整代码 (opens new window)