一篇搞懂Webpack常用的配置
1.认识 Webpack
Webpack 是什么?
- 官方的定义
Webpack是一个用于现代JavaScript应用程序的 静态模块打包工具。- 当
Webpack处理应用程序时, - 它会在内部从一个或多个入口点构建一个 依赖图(
dependency graph) - 然后将你项目中所需的每一个模块组合成一个或多个
bundles,它们均为静态资源,用于展示你的内容
- 简单的说
- 之前
- 在
2010年左右,前端当时还是利用jQuery进行开发 - 后端利用
php jsp等技术将数据库的数据渲染到前端的页面上 - 前后端开始是耦合的 维护和开发 都是一个不规范 繁琐的流程
- 在
- 现在
- 当三大框架的横行后 逐渐以
MVVM(Model-View-ViewModel)模式来 - 减少繁琐的
DOM操作,以数据来驱动视图的变化,更加利于维护和开发
- 当三大框架的横行后 逐渐以
- 为什么使用
- 原生
js不会提供所有的特性, 因此就需要引入各种插件 - 而
Webpack就是大一统的集成方案
- 原生
- 之前
Webpack 可以做什么
- 使用
Webpack作为前端构建工具通常可以做到以下几个方面的事情- 代码转换:
TypeScript编译成JavaScript、SCSS编译成CSS等。 - 文件优化: 压缩
JavaScript、CSS、HTML代码,压缩合并图片等。 - 代码分割: 提取多个页面的公共代码、提取首屏不需要执行部分的代码让其异步加载。
- 模块合并: 在采用模块化的项目里会有很多个模块和文件,需要构建功能把模块分类合并成一个文件。
- 自动刷新: 监听本地源代码的变化,自动重新构建、刷新浏览器页面,通常叫做模块热替换
HMR。 - 代码校验: 在代码被提交到仓库前需要校验代码是否符合规范,以及单元测试是否通过。
- 自动发布: 更新完代码后,自动构建出线上发布代码并传输给发布系统。
- 代码转换:
2.搭建 Webpack
搭建基本环境
- 安装最新的环境, 新建一个文件夹叫
test test根路径下载基本的依赖1
2
3yarn add webpack webpack-cli --save-dev
yarn add webpack-dev-server -D
yarn add html-webpack-plugin --save-dev- 在
test/package.json文件添加启动和打包的shell命令1
2
3
4"scripts": {
"serve": "webpack serve ",
"build": "webpack"
}, - 新建基本的文件
1
2
3
4
5
6
7
8
9
10# dist 目录不用手动创建 这个是打包自动生成的
|-- node_modules
├── dist
│ └── main.js
├── public
│ └── index.html
├── package.json
├── src
│ └── index.js
└── webpack.config.js - 在 webpack.config.js 文件写入基本的配置
1
2
3
4
5
6
7
8
9
10
11# 这些配置后面会具体解释 这里主要配置了打包的出口文件和入口文件
# webpack.config.js
const path = require('path')
module.exports = {
entry: './src/index.js',
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist'),
},
mode: "development"
}
测试
此时就完成了基本的搭建,可以来使用shell语句测试一下效果了
- 在
/src/index.js写入console.log('Hello Webpck'); - 然后在项目根路径执行之前在
package.json定义的shell命令 yarn build就在在/dist/main.js发现转换后的代码了- 但是目前还是不能展示html页面 和 启动服务
- 在下一阶段就将安装两个必要的插件
1 | /* |
3.配置插件
导读
- 自己可以去
npm搜索各种loader获取更多具体的配置 - 这里仅仅配置了我用过的常用配置
- npm-loader
- 配置插件章节的项目最终结构
目录结构
1 | . |
index.html
1 | ./public/index.html |
index.js
1 | # ./src/index.js |
index.less
1 | # ./src/index.less |
webpack.config.js
1 | # ./webpack.config.js |
package.json
1 | # package.json |
webpack-dev-server
- 这个插件其实就是一个小型的本地服务器
- 相关配置也比较简单
- 其他的具体配置后面再说
- 这时候就可以执行
yarn serve - 此时还没有配置解析html的插件 因此先手动跳转到
main.js测试下 http://localhost:8088/main.js1
2
3
4
5
6
7
8
9
10
11
12
13
14yarn add webpack-dev-server -D
# webpack.config.js
const path = require('path')
module.exports = {
...
devServer: {
// 启动gzip压缩
compress: true,
// 打开的端口
port: 8088,
// 启动服务后自动打开网页
open: true
}
}
html-webpack-plugin
- 这个包显然就是用来解析html的
- 配置后运行
yarn build就可以在dist目录看到打包后的index.html了 - 同时运行
yarn serve也可以直接运行解析了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
37yarn add html-webpack-plugin -D
# 在 ./public/index.html 随便写点东西
<body>
html5
<img id='im' src="" alt="">
</body>
# webpack.config.js
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
entry: './src/index.js',
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist'),
},
mode: "development",
devServer: {
// 启动gzip压缩
compress: true,
port: 8088,
open: true
},
plugins: [
new HtmlWebpackPlugin({
// 要生成的index.html路径
template: './public/index.html',
//要生成的文件名 存在内存 目录中不显示
filename: 'index.html',
minify: {
// 移除空格
collapseWhitespace: true,
// 移除注释
removeComments: true
}
})
]
}此时我们完成了基本的架构,现在需要配置各种loader来满足项目的需要
Asset Modules
Asset Modules是一种模块,它允许人们在不配置额外加载器的情况下使用资产文件(字体、图标等)webpack5不需要再去手动下载三个loader了- 在
webpack 5之前,通常使用:raw-loader将文件作为字符串导入url-loader将文件作为数据 URI 内联到包中file-loader将文件发送到输出目录
Asset Modules分为4中资源模块asset/resource将资源分割为单独的文件,并导出url,就是之前的file-loader的功能asset/inline将资源导出为dataURL(url(data:))的形式,之前的url-loader的功能asset/source将资源导出为源码(source code). 之前的raw-loader功能asset自动选择导出为单独文件或者dataURL形式(默认为8KB). 之前有url-loader设置asset size limit限制实现。
- 当配置完成后运行 yarn build就会发现 图片也被打包进了dist目录
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
59
60
61
62
63
64
65
66# 在 ./public 放一张图片 这里选择了avatar.png
# ./src/index.js
import avatar from '../public/avatar.png'
const im = document.getElementById('im')
im.src = avatar
console.log('Hello Webpck');
# webpack.config.js => module.exports.use
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
entry: './src/index.js',
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist'),
// 指定打包后输出的文件夹 ./dist/public/assets/images
assetModuleFilename: 'public/assets/images/[hash][ext][query]'
},
mode: "development",
devServer: {
// 启动gzip压缩
compress: true,
port: 8088,
open: true
},
plugins: [
new HtmlWebpackPlugin({
template: './public/index.html',
//要生成的文件名 存在内存 目录中不显示
filename: 'index.html',
minify: {
// 移除空格
collapseWhitespace: true,
// 移除注释
removeComments: true
}
})
],
module: {
rules: [
{
test: /\.(?:ico|gif|png|jpg|jpeg)$/i,
type: 'asset/resource',
},
// {
// test: /\.html/,
// type: 'asset/resource',
// generator: {
// filename: 'public/static/[hash][ext][query]' // 单独指定名字
// }
// },
{
test: /\.svg/,
type: 'asset/inline' // inline 的时候不需要指定文件名
},
{
test: /\.txt/,
type: 'asset',
parser: {
dataUrlCondition: {
maxSize: 4 * 1024 // 4kb 指定大小
}
}
}
],
},
}
babel-loader
babel-loader用于转化和识别高级语法- 当配置完成后运行
yarn build可以查看./dist/main.js后可以发现- 代码已经将箭头函数转换成了
es5了 var aaaa = function aaaa() {\n return 10;\n};\n\nconsole.log(aaaa);- 然后注销掉
babel-loader的规则 重新打包 - 你会发现
main.js中还是箭头函数 这就是babel-loader的作用之一1
2
3
4
5
6
7
8
9
10
11
12
13
14
15npm install -D babel-loader @babel/core @babel/preset-env
在 ./src/index.js 加入一个 es6 箭头函数
const aaaa = () => 10
console.log(aaaa);
# webpack.config.js => module.exports.module.rules.xxx
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env']
}
}
},
- 代码已经将箭头函数转换成了
css,sass,less,postcss loader
sass less大家都知道是css的预编译语言就不用多说了postcss是用于自动添加css的兼容前缀- 接下来就一次性安装多个
loader- 不过注意
node-sass的上游依赖需要手动配置镜像或代理 否则一直可能下载失败node-sass配置镜像
- 不过注意
- 配置完成后 就可以看到
less-loader生效了 - 其他的
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
33
34
35
36
37
38yarn add style-loader css-loader -D
yarn add less-loader less -D
yarn add sass-loader node-sass -D
yarn add postcss-loader autoprefixer -D
# ./public/index.html
ul>li{$}*3
# ./src/index.js
import './index.less'
# ./src/index.less
@myColor: blue;
li{
color: @myColor;
}
# webpack.config.js => module.exports.module.rules.xxx
{
test: /\.css$/,
use: [
'style-loader',
'css-loader',
'postcss-loader'
]
},
{
test: /\.less$/,
use: [
'style-loader',
'css-loader',
'less-loader',
]
},
{
test: /\.scss$/,
use: [
'style-loader',
'css-loader',
'sass-loader'
]
}
4. configuration
版本事项
以下的这些配置基于 webpack 4.x, 当使用webpack5 时可能有一些变动
entry
1 | # 新建目录src |
output
1 | 默认出口: ./dist/main.js |
mode
1 | module.exports = { |
devServer
1 | module.exports = { |
module
noParse
1 | module.exports = { |
rules
1 | module.exports = { |
oneOf
1 | // 当规则匹配时 只使用第一个成功的匹配规则 |
resolve
alias
1 | const path = require('path') |
extensions modules
1 | module.exports = { |
plugins
1 | module.exports = { |
externals
1 | // 拒绝 jqery 被打包 |
Optimization
splitChunks
1 | // 将 node_modules 中代码打包进一个 chunk |
devtool
source-map
1 | module.exports = { |
4. demo
css抽离
1 | plugins: [ |
js抽离
1 | output: { |
js语法检查
1 | # |
代码切割
1 | 1. 多入口 自动打包多个文件 |
dll
1 | # |
1 | externals: { |
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 LiuYuanhua!
评论