push doc
This commit is contained in:
12
docs/senior/README.md
Normal file
12
docs/senior/README.md
Normal file
@@ -0,0 +1,12 @@
|
||||
# 介绍
|
||||
|
||||
本章节主要介绍 Webpack 高级配置。
|
||||
|
||||
所谓高级配置其实就是进行 Webpack 优化,让我们代码在编译/运行时性能更好~
|
||||
|
||||
我们会从以下角度来进行优化:
|
||||
|
||||
1. 提升开发体验
|
||||
2. 提升打包构建速度
|
||||
3. 减少代码体积
|
||||
4. 优化代码运行性能
|
||||
75
docs/senior/enhanceExperience.md
Normal file
75
docs/senior/enhanceExperience.md
Normal file
@@ -0,0 +1,75 @@
|
||||
# 提升开发体验
|
||||
|
||||
## SourceMap
|
||||
|
||||
### 为什么
|
||||
|
||||
开发时我们运行的代码是经过 webpack 编译后的,例如下面这个样子:
|
||||
|
||||
```js
|
||||
/*
|
||||
* ATTENTION: The "eval" devtool has been used (maybe by default in mode: "development").
|
||||
* This devtool is neither made for production nor for readable output files.
|
||||
* It uses "eval()" calls to create a separate source file in the browser devtools.
|
||||
* If you are trying to read the output file, select a different devtool (https://webpack.js.org/configuration/devtool/)
|
||||
* or disable the default devtool with "devtool: false".
|
||||
* If you are looking for production-ready output files, see mode: "production" (https://webpack.js.org/configuration/mode/).
|
||||
*/
|
||||
/******/ (() => { // webpackBootstrap
|
||||
/******/ "use strict";
|
||||
/******/ var __webpack_modules__ = ({
|
||||
|
||||
/***/ "./node_modules/css-loader/dist/cjs.js!./node_modules/less-loader/dist/cjs.js!./src/less/index.less":
|
||||
/*!**********************************************************************************************************!*\
|
||||
!*** ./node_modules/css-loader/dist/cjs.js!./node_modules/less-loader/dist/cjs.js!./src/less/index.less ***!
|
||||
\**********************************************************************************************************/
|
||||
/***/ ((module, __webpack_exports__, __webpack_require__) => {
|
||||
|
||||
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (__WEBPACK_DEFAULT_EXPORT__)\n/* harmony export */ });\n/* harmony import */ var _node_modules_css_loader_dist_runtime_noSourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../node_modules/css-loader/dist/runtime/noSourceMaps.js */ \"./node_modules/css-loader/dist/runtime/noSourceMaps.js\");\n/* harmony import */ var _node_modules_css_loader_dist_runtime_noSourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_noSourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);\n/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../node_modules/css-loader/dist/runtime/api.js */ \"./node_modules/css-loader/dist/runtime/api.js\");\n/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);\n// Imports\n\n\nvar ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_noSourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));\n// Module\n___CSS_LOADER_EXPORT___.push([module.id, \".box2 {\\n width: 100px;\\n height: 100px;\\n background-color: deeppink;\\n}\\n\", \"\"]);\n// Exports\n/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);\n\n\n//# sourceURL=webpack://webpack5/./src/less/index.less?./node_modules/css-loader/dist/cjs.js!./node_modules/less-loader/dist/cjs.js");
|
||||
|
||||
/***/ }),
|
||||
// 其他省略
|
||||
```
|
||||
|
||||
所有 css 和 js 合并成了一个文件,并且多了其他代码。此时如果代码运行出错那么提示代码错误位置我们是看不懂的。一旦将来开发代码文件很多,那么很难去发现错误出现在哪里。
|
||||
|
||||
所以我们需要更加准确的错误提示,来帮助我们更好的开发代码。
|
||||
|
||||
### 是什么
|
||||
|
||||
SourceMap(源代码映射)是一个用来生成源代码与构建后代码一一映射的文件的方案。
|
||||
|
||||
它会生成一个 xxx.map 文件,里面包含源代码和构建后代码每一行、每一列的映射关系。当构建后代码出错了,会通过 xxx.map 文件,从构建后代码出错位置找到映射后源代码出错位置,从而让浏览器提示源代码文件出错位置,帮助我们更快的找到错误根源。
|
||||
|
||||
### 怎么用
|
||||
|
||||
通过查看[Webpack DevTool 文档](https://webpack.docschina.org/configuration/devtool/)可知,SourceMap 的值有很多种情况.
|
||||
|
||||
但实际开发时我们只需要关注两种情况即可:
|
||||
|
||||
- 开发模式:`cheap-module-source-map`
|
||||
|
||||
- 优点:打包编译速度快,只包含行映射
|
||||
- 缺点:没有列映射
|
||||
|
||||
```js
|
||||
module.exports = {
|
||||
// 其他省略
|
||||
mode: "development",
|
||||
devtool: "cheap-module-source-map",
|
||||
};
|
||||
```
|
||||
|
||||
- 生产模式:`source-map`
|
||||
- 优点:包含行/列映射
|
||||
- 缺点:打包编译速度更慢
|
||||
|
||||
```js
|
||||
module.exports = {
|
||||
// 其他省略
|
||||
mode: "production",
|
||||
devtool: "source-map",
|
||||
};
|
||||
```
|
||||
|
||||
|
||||
598
docs/senior/liftingSpeed.md
Normal file
598
docs/senior/liftingSpeed.md
Normal file
@@ -0,0 +1,598 @@
|
||||
# 提升打包构建速度
|
||||
|
||||
## HotModuleReplacement
|
||||
|
||||
### 为什么
|
||||
|
||||
开发时我们修改了其中一个模块代码,Webpack 默认会将所有模块全部重新打包编译,速度很慢。
|
||||
|
||||
所以我们需要做到修改某个模块代码,就只有这个模块代码需要重新打包编译,其他模块不变,这样打包速度就能很快。
|
||||
|
||||
### 是什么
|
||||
|
||||
HotModuleReplacement(HMR/热模块替换):在程序运行中,替换、添加或删除模块,而无需重新加载整个页面。
|
||||
|
||||
### 怎么用
|
||||
|
||||
1. 基本配置
|
||||
|
||||
```js
|
||||
module.exports = {
|
||||
// 其他省略
|
||||
devServer: {
|
||||
host: "localhost", // 启动服务器域名
|
||||
port: "3000", // 启动服务器端口号
|
||||
open: true, // 是否自动打开浏览器
|
||||
hot: true, // 开启HMR功能(只能用于开发环境,生产环境不需要了)
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
此时 css 样式经过 style-loader 处理,已经具备 HMR 功能了。
|
||||
但是 js 还不行。
|
||||
|
||||
2. JS 配置
|
||||
|
||||
```js{17-28}
|
||||
// main.js
|
||||
import count from "./js/count";
|
||||
import sum from "./js/sum";
|
||||
// 引入资源,Webpack才会对其打包
|
||||
import "./css/iconfont.css";
|
||||
import "./css/index.css";
|
||||
import "./less/index.less";
|
||||
import "./sass/index.sass";
|
||||
import "./sass/index.scss";
|
||||
import "./styl/index.styl";
|
||||
|
||||
const result1 = count(2, 1);
|
||||
console.log(result1);
|
||||
const result2 = sum(1, 2, 3, 4);
|
||||
console.log(result2);
|
||||
|
||||
// 判断是否支持HMR功能
|
||||
if (module.hot) {
|
||||
module.hot.accept("./js/count.js", function (count) {
|
||||
const result1 = count(2, 1);
|
||||
console.log(result1);
|
||||
});
|
||||
|
||||
module.hot.accept("./js/sum.js", function (sum) {
|
||||
const result2 = sum(1, 2, 3, 4);
|
||||
console.log(result2);
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
上面这样写会很麻烦,所以实际开发我们会使用其他 loader 来解决。
|
||||
|
||||
比如:[vue-loader](https://github.com/vuejs/vue-loader), [react-hot-loader](https://github.com/gaearon/react-hot-loader)。
|
||||
|
||||
## OneOf
|
||||
|
||||
### 为什么
|
||||
|
||||
打包时每个文件都会经过所有 loader 处理,虽然因为 `test` 正则原因实际没有处理上,但是都要过一遍。比较慢。
|
||||
|
||||
### 是什么
|
||||
|
||||
顾名思义就是只能匹配上一个 loader, 剩下的就不匹配了。
|
||||
|
||||
### 怎么用
|
||||
|
||||
```js
|
||||
const path = require("path");
|
||||
const ESLintWebpackPlugin = require("eslint-webpack-plugin");
|
||||
const HtmlWebpackPlugin = require("html-webpack-plugin");
|
||||
|
||||
module.exports = {
|
||||
entry: "./src/main.js",
|
||||
output: {
|
||||
path: undefined, // 开发模式没有输出,不需要指定输出目录
|
||||
filename: "static/js/main.js", // 将 js 文件输出到 static/js 目录中
|
||||
// clean: true, // 开发模式没有输出,不需要清空输出结果
|
||||
},
|
||||
module: {
|
||||
rules: [
|
||||
{
|
||||
oneOf: [
|
||||
{
|
||||
// 用来匹配 .css 结尾的文件
|
||||
test: /\.css$/,
|
||||
// use 数组里面 Loader 执行顺序是从右到左
|
||||
use: ["style-loader", "css-loader"],
|
||||
},
|
||||
{
|
||||
test: /\.less$/,
|
||||
use: ["style-loader", "css-loader", "less-loader"],
|
||||
},
|
||||
{
|
||||
test: /\.s[ac]ss$/,
|
||||
use: ["style-loader", "css-loader", "sass-loader"],
|
||||
},
|
||||
{
|
||||
test: /\.styl$/,
|
||||
use: ["style-loader", "css-loader", "stylus-loader"],
|
||||
},
|
||||
{
|
||||
test: /\.(png|jpe?g|gif|webp)$/,
|
||||
type: "asset",
|
||||
parser: {
|
||||
dataUrlCondition: {
|
||||
maxSize: 10 * 1024, // 小于10kb的图片会被base64处理
|
||||
},
|
||||
},
|
||||
generator: {
|
||||
// 将图片文件输出到 static/imgs 目录中
|
||||
// 将图片文件命名 [hash:8][ext][query]
|
||||
// [hash:8]: hash值取8位
|
||||
// [ext]: 使用之前的文件扩展名
|
||||
// [query]: 添加之前的query参数
|
||||
filename: "static/imgs/[hash:8][ext][query]",
|
||||
},
|
||||
},
|
||||
{
|
||||
test: /\.(ttf|woff2?)$/,
|
||||
type: "asset/resource",
|
||||
generator: {
|
||||
filename: "static/media/[hash:8][ext][query]",
|
||||
},
|
||||
},
|
||||
{
|
||||
test: /\.js$/,
|
||||
exclude: /node_modules/, // 排除node_modules代码不编译
|
||||
loader: "babel-loader",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
plugins: [
|
||||
new ESLintWebpackPlugin({
|
||||
// 指定检查文件的根目录
|
||||
context: path.resolve(__dirname, "../src"),
|
||||
}),
|
||||
new HtmlWebpackPlugin({
|
||||
// 以 public/index.html 为模板创建文件
|
||||
// 新的html文件有两个特点:1. 内容和源文件一致 2. 自动引入打包生成的js等资源
|
||||
template: path.resolve(__dirname, "../public/index.html"),
|
||||
}),
|
||||
],
|
||||
// 开发服务器
|
||||
devServer: {
|
||||
host: "localhost", // 启动服务器域名
|
||||
port: "3000", // 启动服务器端口号
|
||||
open: true, // 是否自动打开浏览器
|
||||
hot: true, // 开启HMR功能
|
||||
},
|
||||
mode: "development",
|
||||
devtool: "cheap-module-source-map",
|
||||
};
|
||||
```
|
||||
|
||||
生产模式也是如此配置。
|
||||
|
||||
## Include/Exclude
|
||||
|
||||
### 为什么
|
||||
|
||||
开发时我们需要使用第三方的库或插件,所有文件都下载到 node_modules 中了。而这些文件是不需要编译可以直接使用的。
|
||||
|
||||
所以我们在对 js 文件处理时,要排除 node_modules 下面的文件。
|
||||
|
||||
### 是什么
|
||||
|
||||
- include
|
||||
|
||||
包含,只处理 xxx 文件
|
||||
|
||||
- exclude
|
||||
|
||||
排除,除了 xxx 文件以外其他文件都处理
|
||||
|
||||
### 怎么用
|
||||
|
||||
```js{60-61,72}
|
||||
const path = require("path");
|
||||
const ESLintWebpackPlugin = require("eslint-webpack-plugin");
|
||||
const HtmlWebpackPlugin = require("html-webpack-plugin");
|
||||
|
||||
module.exports = {
|
||||
entry: "./src/main.js",
|
||||
output: {
|
||||
path: undefined, // 开发模式没有输出,不需要指定输出目录
|
||||
filename: "static/js/main.js", // 将 js 文件输出到 static/js 目录中
|
||||
// clean: true, // 开发模式没有输出,不需要清空输出结果
|
||||
},
|
||||
module: {
|
||||
rules: [
|
||||
{
|
||||
oneOf: [
|
||||
{
|
||||
// 用来匹配 .css 结尾的文件
|
||||
test: /\.css$/,
|
||||
// use 数组里面 Loader 执行顺序是从右到左
|
||||
use: ["style-loader", "css-loader"],
|
||||
},
|
||||
{
|
||||
test: /\.less$/,
|
||||
use: ["style-loader", "css-loader", "less-loader"],
|
||||
},
|
||||
{
|
||||
test: /\.s[ac]ss$/,
|
||||
use: ["style-loader", "css-loader", "sass-loader"],
|
||||
},
|
||||
{
|
||||
test: /\.styl$/,
|
||||
use: ["style-loader", "css-loader", "stylus-loader"],
|
||||
},
|
||||
{
|
||||
test: /\.(png|jpe?g|gif|webp)$/,
|
||||
type: "asset",
|
||||
parser: {
|
||||
dataUrlCondition: {
|
||||
maxSize: 10 * 1024, // 小于10kb的图片会被base64处理
|
||||
},
|
||||
},
|
||||
generator: {
|
||||
// 将图片文件输出到 static/imgs 目录中
|
||||
// 将图片文件命名 [hash:8][ext][query]
|
||||
// [hash:8]: hash值取8位
|
||||
// [ext]: 使用之前的文件扩展名
|
||||
// [query]: 添加之前的query参数
|
||||
filename: "static/imgs/[hash:8][ext][query]",
|
||||
},
|
||||
},
|
||||
{
|
||||
test: /\.(ttf|woff2?)$/,
|
||||
type: "asset/resource",
|
||||
generator: {
|
||||
filename: "static/media/[hash:8][ext][query]",
|
||||
},
|
||||
},
|
||||
{
|
||||
test: /\.js$/,
|
||||
// exclude: /node_modules/, // 排除node_modules代码不编译
|
||||
include: path.resolve(__dirname, "../src"), // 也可以用包含
|
||||
loader: "babel-loader",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
plugins: [
|
||||
new ESLintWebpackPlugin({
|
||||
// 指定检查文件的根目录
|
||||
context: path.resolve(__dirname, "../src"),
|
||||
exclude: "node_modules", // 默认值
|
||||
}),
|
||||
new HtmlWebpackPlugin({
|
||||
// 以 public/index.html 为模板创建文件
|
||||
// 新的html文件有两个特点:1. 内容和源文件一致 2. 自动引入打包生成的js等资源
|
||||
template: path.resolve(__dirname, "../public/index.html"),
|
||||
}),
|
||||
],
|
||||
// 开发服务器
|
||||
devServer: {
|
||||
host: "localhost", // 启动服务器域名
|
||||
port: "3000", // 启动服务器端口号
|
||||
open: true, // 是否自动打开浏览器
|
||||
hot: true, // 开启HMR功能
|
||||
},
|
||||
mode: "development",
|
||||
devtool: "cheap-module-source-map",
|
||||
};
|
||||
```
|
||||
|
||||
生产模式也是如此配置。
|
||||
|
||||
## Cache
|
||||
|
||||
### 为什么
|
||||
|
||||
每次打包时 js 文件都要经过 Eslint 检查 和 Babel 编译,速度比较慢。
|
||||
|
||||
我们可以缓存之前的 Eslint 检查 和 Babel 编译结果,这样第二次打包时速度就会更快了。
|
||||
|
||||
### 是什么
|
||||
|
||||
对 Eslint 检查 和 Babel 编译结果进行缓存。
|
||||
|
||||
### 怎么用
|
||||
|
||||
```js{63-66,77-82}
|
||||
const path = require("path");
|
||||
const ESLintWebpackPlugin = require("eslint-webpack-plugin");
|
||||
const HtmlWebpackPlugin = require("html-webpack-plugin");
|
||||
|
||||
module.exports = {
|
||||
entry: "./src/main.js",
|
||||
output: {
|
||||
path: undefined, // 开发模式没有输出,不需要指定输出目录
|
||||
filename: "static/js/main.js", // 将 js 文件输出到 static/js 目录中
|
||||
// clean: true, // 开发模式没有输出,不需要清空输出结果
|
||||
},
|
||||
module: {
|
||||
rules: [
|
||||
{
|
||||
oneOf: [
|
||||
{
|
||||
// 用来匹配 .css 结尾的文件
|
||||
test: /\.css$/,
|
||||
// use 数组里面 Loader 执行顺序是从右到左
|
||||
use: ["style-loader", "css-loader"],
|
||||
},
|
||||
{
|
||||
test: /\.less$/,
|
||||
use: ["style-loader", "css-loader", "less-loader"],
|
||||
},
|
||||
{
|
||||
test: /\.s[ac]ss$/,
|
||||
use: ["style-loader", "css-loader", "sass-loader"],
|
||||
},
|
||||
{
|
||||
test: /\.styl$/,
|
||||
use: ["style-loader", "css-loader", "stylus-loader"],
|
||||
},
|
||||
{
|
||||
test: /\.(png|jpe?g|gif|webp)$/,
|
||||
type: "asset",
|
||||
parser: {
|
||||
dataUrlCondition: {
|
||||
maxSize: 10 * 1024, // 小于10kb的图片会被base64处理
|
||||
},
|
||||
},
|
||||
generator: {
|
||||
// 将图片文件输出到 static/imgs 目录中
|
||||
// 将图片文件命名 [hash:8][ext][query]
|
||||
// [hash:8]: hash值取8位
|
||||
// [ext]: 使用之前的文件扩展名
|
||||
// [query]: 添加之前的query参数
|
||||
filename: "static/imgs/[hash:8][ext][query]",
|
||||
},
|
||||
},
|
||||
{
|
||||
test: /\.(ttf|woff2?)$/,
|
||||
type: "asset/resource",
|
||||
generator: {
|
||||
filename: "static/media/[hash:8][ext][query]",
|
||||
},
|
||||
},
|
||||
{
|
||||
test: /\.js$/,
|
||||
// exclude: /node_modules/, // 排除node_modules代码不编译
|
||||
include: path.resolve(__dirname, "../src"), // 也可以用包含
|
||||
loader: "babel-loader",
|
||||
options: {
|
||||
cacheDirectory: true, // 开启babel编译缓存
|
||||
cacheCompression: false, // 缓存文件不要压缩
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
plugins: [
|
||||
new ESLintWebpackPlugin({
|
||||
// 指定检查文件的根目录
|
||||
context: path.resolve(__dirname, "../src"),
|
||||
exclude: "node_modules", // 默认值
|
||||
cache: true, // 开启缓存
|
||||
// 缓存目录
|
||||
cacheLocation: path.resolve(
|
||||
__dirname,
|
||||
"../node_modules/.cache/.eslintcache"
|
||||
),
|
||||
}),
|
||||
new HtmlWebpackPlugin({
|
||||
// 以 public/index.html 为模板创建文件
|
||||
// 新的html文件有两个特点:1. 内容和源文件一致 2. 自动引入打包生成的js等资源
|
||||
template: path.resolve(__dirname, "../public/index.html"),
|
||||
}),
|
||||
],
|
||||
// 开发服务器
|
||||
devServer: {
|
||||
host: "localhost", // 启动服务器域名
|
||||
port: "3000", // 启动服务器端口号
|
||||
open: true, // 是否自动打开浏览器
|
||||
hot: true, // 开启HMR功能
|
||||
},
|
||||
mode: "development",
|
||||
devtool: "cheap-module-source-map",
|
||||
};
|
||||
```
|
||||
|
||||
## Thead
|
||||
|
||||
### 为什么
|
||||
|
||||
当项目越来越庞大时,打包速度越来越慢,甚至于需要一个下午才能打包出来代码。这个速度是比较慢的。
|
||||
|
||||
我们想要继续提升打包速度,其实就是要提升 js 的打包速度,因为其他文件都比较少。
|
||||
|
||||
而对 js 文件处理主要就是 eslint 、babel、Terser 三个工具,所以我们要提升它们的运行速度。
|
||||
|
||||
我们可以开启多进程同时处理 js 文件,这样速度就比之前的单进程打包更快了。
|
||||
|
||||
### 是什么
|
||||
|
||||
多进程打包:开启电脑的多个进程同时干一件事,速度更快。
|
||||
|
||||
**需要注意:请仅在特别耗时的操作中使用,因为每个进程启动就有大约为 600ms 左右开销。**
|
||||
|
||||
### 怎么用
|
||||
|
||||
我们启动进程的数量就是我们 CPU 的核数。
|
||||
|
||||
1. 如何获取 CPU 的核数,因为每个电脑都不一样。
|
||||
|
||||
```js
|
||||
// nodejs核心模块,直接使用
|
||||
const os = require("os");
|
||||
// cpu核数
|
||||
const threads = os.cpus().length;
|
||||
```
|
||||
|
||||
2. 下载包
|
||||
|
||||
```
|
||||
npm i thread-loader -D
|
||||
```
|
||||
|
||||
3. 使用
|
||||
|
||||
```js{1,7,9-10,88-101,118,131,133-143}
|
||||
const os = require("os");
|
||||
const path = require("path");
|
||||
const ESLintWebpackPlugin = require("eslint-webpack-plugin");
|
||||
const HtmlWebpackPlugin = require("html-webpack-plugin");
|
||||
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
|
||||
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
|
||||
const TerserPlugin = require("terser-webpack-plugin");
|
||||
|
||||
// cpu核数
|
||||
const threads = os.cpus().length;
|
||||
|
||||
// 获取处理样式的Loaders
|
||||
const getStyleLoaders = (preProcessor) => {
|
||||
return [
|
||||
MiniCssExtractPlugin.loader,
|
||||
"css-loader",
|
||||
{
|
||||
loader: "postcss-loader",
|
||||
options: {
|
||||
postcssOptions: {
|
||||
plugins: [
|
||||
"postcss-preset-env", // 能解决大多数样式兼容性问题
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
preProcessor,
|
||||
].filter(Boolean);
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
entry: "./src/main.js",
|
||||
output: {
|
||||
path: path.resolve(__dirname, "../dist"), // 生产模式需要输出
|
||||
filename: "static/js/main.js", // 将 js 文件输出到 static/js 目录中
|
||||
clean: true,
|
||||
},
|
||||
module: {
|
||||
rules: [
|
||||
{
|
||||
oneOf: [
|
||||
{
|
||||
// 用来匹配 .css 结尾的文件
|
||||
test: /\.css$/,
|
||||
// use 数组里面 Loader 执行顺序是从右到左
|
||||
use: getStyleLoaders(),
|
||||
},
|
||||
{
|
||||
test: /\.less$/,
|
||||
use: getStyleLoaders("less-loader"),
|
||||
},
|
||||
{
|
||||
test: /\.s[ac]ss$/,
|
||||
use: getStyleLoaders("sass-loader"),
|
||||
},
|
||||
{
|
||||
test: /\.styl$/,
|
||||
use: getStyleLoaders("stylus-loader"),
|
||||
},
|
||||
{
|
||||
test: /\.(png|jpe?g|gif|webp)$/,
|
||||
type: "asset",
|
||||
parser: {
|
||||
dataUrlCondition: {
|
||||
maxSize: 10 * 1024, // 小于10kb的图片会被base64处理
|
||||
},
|
||||
},
|
||||
generator: {
|
||||
// 将图片文件输出到 static/imgs 目录中
|
||||
// 将图片文件命名 [hash:8][ext][query]
|
||||
// [hash:8]: hash值取8位
|
||||
// [ext]: 使用之前的文件扩展名
|
||||
// [query]: 添加之前的query参数
|
||||
filename: "static/imgs/[hash:8][ext][query]",
|
||||
},
|
||||
},
|
||||
{
|
||||
test: /\.(ttf|woff2?)$/,
|
||||
type: "asset/resource",
|
||||
generator: {
|
||||
filename: "static/media/[hash:8][ext][query]",
|
||||
},
|
||||
},
|
||||
{
|
||||
test: /\.js$/,
|
||||
// exclude: /node_modules/, // 排除node_modules代码不编译
|
||||
include: path.resolve(__dirname, "../src"), // 也可以用包含
|
||||
use: [
|
||||
{
|
||||
loader: "thread-loader", // 开启多进程
|
||||
options: {
|
||||
workers: threads, // 数量
|
||||
},
|
||||
},
|
||||
{
|
||||
loader: "babel-loader",
|
||||
options: {
|
||||
cacheDirectory: true, // 开启babel编译缓存
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
plugins: [
|
||||
new ESLintWebpackPlugin({
|
||||
// 指定检查文件的根目录
|
||||
context: path.resolve(__dirname, "../src"),
|
||||
exclude: "node_modules", // 默认值
|
||||
cache: true, // 开启缓存
|
||||
// 缓存目录
|
||||
cacheLocation: path.resolve(
|
||||
__dirname,
|
||||
"../node_modules/.cache/.eslintcache"
|
||||
),
|
||||
threads, // 开启多进程
|
||||
}),
|
||||
new HtmlWebpackPlugin({
|
||||
// 以 public/index.html 为模板创建文件
|
||||
// 新的html文件有两个特点:1. 内容和源文件一致 2. 自动引入打包生成的js等资源
|
||||
template: path.resolve(__dirname, "../public/index.html"),
|
||||
}),
|
||||
// 提取css成单独文件
|
||||
new MiniCssExtractPlugin({
|
||||
// 定义输出文件名和目录
|
||||
filename: "static/css/main.css",
|
||||
}),
|
||||
// css压缩
|
||||
// new CssMinimizerPlugin(),
|
||||
],
|
||||
optimization: {
|
||||
minimize: true,
|
||||
minimizer: [
|
||||
// css压缩也可以写到optimization.minimizer里面,效果一样的
|
||||
new CssMinimizerPlugin(),
|
||||
// 当生产模式会默认开启TerserPlugin,但是我们需要进行其他配置,就要重新写了
|
||||
new TerserPlugin({
|
||||
parallel: threads // 开启多进程
|
||||
})
|
||||
],
|
||||
},
|
||||
// devServer: {
|
||||
// host: "localhost", // 启动服务器域名
|
||||
// port: "3000", // 启动服务器端口号
|
||||
// open: true, // 是否自动打开浏览器
|
||||
// },
|
||||
mode: "production",
|
||||
devtool: "source-map",
|
||||
};
|
||||
```
|
||||
|
||||
我们目前打包的内容都很少,所以因为启动进程开销原因,使用多进程打包实际上会显著的让我们打包时间变得很长。
|
||||
1969
docs/senior/optimizePerformance.md
Normal file
1969
docs/senior/optimizePerformance.md
Normal file
File diff suppressed because it is too large
Load Diff
448
docs/senior/reduceVolume.md
Normal file
448
docs/senior/reduceVolume.md
Normal file
@@ -0,0 +1,448 @@
|
||||
# 减少代码体积
|
||||
|
||||
## Tree Shaking
|
||||
|
||||
### 为什么
|
||||
|
||||
开发时我们定义了一些工具函数库,或者引用第三方工具函数库或组件库。
|
||||
|
||||
如果没有特殊处理的话我们打包时会引入整个库,但是实际上可能我们可能只用上极小部分的功能。
|
||||
|
||||
这样将整个库都打包进来,体积就太大了。
|
||||
|
||||
### 是什么
|
||||
|
||||
`Tree Shaking` 是一个术语,通常用于描述移除 JavaScript 中的没有使用上的代码。
|
||||
|
||||
**注意:它依赖 `ES Module`。**
|
||||
|
||||
### 怎么用
|
||||
|
||||
Webpack 已经默认开启了这个功能,无需其他配置。
|
||||
|
||||
## Babel
|
||||
|
||||
### 为什么
|
||||
|
||||
Babel 为编译的每个文件都插入了辅助代码,使代码体积过大!
|
||||
|
||||
Babel 对一些公共方法使用了非常小的辅助代码,比如 `_extend`。默认情况下会被添加到每一个需要它的文件中。
|
||||
|
||||
你可以将这些辅助代码作为一个独立模块,来避免重复引入。
|
||||
|
||||
### 是什么
|
||||
|
||||
`@babel/plugin-transform-runtime`: 禁用了 Babel 自动对每个文件的 runtime 注入,而是引入 `@babel/plugin-transform-runtime` 并且使所有辅助代码从这里引用。
|
||||
|
||||
### 怎么用
|
||||
|
||||
1. 下载包
|
||||
|
||||
```
|
||||
npm i @babel/plugin-transform-runtime -D
|
||||
```
|
||||
|
||||
2. 配置
|
||||
|
||||
```js{100}
|
||||
const os = require("os");
|
||||
const path = require("path");
|
||||
const ESLintWebpackPlugin = require("eslint-webpack-plugin");
|
||||
const HtmlWebpackPlugin = require("html-webpack-plugin");
|
||||
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
|
||||
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
|
||||
const TerserPlugin = require("terser-webpack-plugin");
|
||||
|
||||
// cpu核数
|
||||
const threads = os.cpus().length;
|
||||
|
||||
// 获取处理样式的Loaders
|
||||
const getStyleLoaders = (preProcessor) => {
|
||||
return [
|
||||
MiniCssExtractPlugin.loader,
|
||||
"css-loader",
|
||||
{
|
||||
loader: "postcss-loader",
|
||||
options: {
|
||||
postcssOptions: {
|
||||
plugins: [
|
||||
"postcss-preset-env", // 能解决大多数样式兼容性问题
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
preProcessor,
|
||||
].filter(Boolean);
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
entry: "./src/main.js",
|
||||
output: {
|
||||
path: path.resolve(__dirname, "../dist"), // 生产模式需要输出
|
||||
filename: "static/js/main.js", // 将 js 文件输出到 static/js 目录中
|
||||
clean: true,
|
||||
},
|
||||
module: {
|
||||
rules: [
|
||||
{
|
||||
oneOf: [
|
||||
{
|
||||
// 用来匹配 .css 结尾的文件
|
||||
test: /\.css$/,
|
||||
// use 数组里面 Loader 执行顺序是从右到左
|
||||
use: getStyleLoaders(),
|
||||
},
|
||||
{
|
||||
test: /\.less$/,
|
||||
use: getStyleLoaders("less-loader"),
|
||||
},
|
||||
{
|
||||
test: /\.s[ac]ss$/,
|
||||
use: getStyleLoaders("sass-loader"),
|
||||
},
|
||||
{
|
||||
test: /\.styl$/,
|
||||
use: getStyleLoaders("stylus-loader"),
|
||||
},
|
||||
{
|
||||
test: /\.(png|jpe?g|gif|webp)$/,
|
||||
type: "asset",
|
||||
parser: {
|
||||
dataUrlCondition: {
|
||||
maxSize: 10 * 1024, // 小于10kb的图片会被base64处理
|
||||
},
|
||||
},
|
||||
generator: {
|
||||
// 将图片文件输出到 static/imgs 目录中
|
||||
// 将图片文件命名 [hash:8][ext][query]
|
||||
// [hash:8]: hash值取8位
|
||||
// [ext]: 使用之前的文件扩展名
|
||||
// [query]: 添加之前的query参数
|
||||
filename: "static/imgs/[hash:8][ext][query]",
|
||||
},
|
||||
},
|
||||
{
|
||||
test: /\.(ttf|woff2?)$/,
|
||||
type: "asset/resource",
|
||||
generator: {
|
||||
filename: "static/media/[hash:8][ext][query]",
|
||||
},
|
||||
},
|
||||
{
|
||||
test: /\.js$/,
|
||||
// exclude: /node_modules/, // 排除node_modules代码不编译
|
||||
include: path.resolve(__dirname, "../src"), // 也可以用包含
|
||||
use: [
|
||||
{
|
||||
loader: "thread-loader", // 开启多进程
|
||||
options: {
|
||||
workers: threads, // 数量
|
||||
},
|
||||
},
|
||||
{
|
||||
loader: "babel-loader",
|
||||
options: {
|
||||
cacheDirectory: true, // 开启babel编译缓存
|
||||
cacheCompression: false, // 缓存文件不要压缩
|
||||
plugins: ["@babel/plugin-transform-runtime"], // 减少代码体积
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
plugins: [
|
||||
new ESLintWebpackPlugin({
|
||||
// 指定检查文件的根目录
|
||||
context: path.resolve(__dirname, "../src"),
|
||||
exclude: "node_modules", // 默认值
|
||||
cache: true, // 开启缓存
|
||||
// 缓存目录
|
||||
cacheLocation: path.resolve(
|
||||
__dirname,
|
||||
"../node_modules/.cache/.eslintcache"
|
||||
),
|
||||
threads, // 开启多进程
|
||||
}),
|
||||
new HtmlWebpackPlugin({
|
||||
// 以 public/index.html 为模板创建文件
|
||||
// 新的html文件有两个特点:1. 内容和源文件一致 2. 自动引入打包生成的js等资源
|
||||
template: path.resolve(__dirname, "../public/index.html"),
|
||||
}),
|
||||
// 提取css成单独文件
|
||||
new MiniCssExtractPlugin({
|
||||
// 定义输出文件名和目录
|
||||
filename: "static/css/main.css",
|
||||
}),
|
||||
// css压缩
|
||||
// new CssMinimizerPlugin(),
|
||||
],
|
||||
optimization: {
|
||||
minimizer: [
|
||||
// css压缩也可以写到optimization.minimizer里面,效果一样的
|
||||
new CssMinimizerPlugin(),
|
||||
// 当生产模式会默认开启TerserPlugin,但是我们需要进行其他配置,就要重新写了
|
||||
new TerserPlugin({
|
||||
parallel: threads, // 开启多进程
|
||||
}),
|
||||
]
|
||||
],
|
||||
// devServer: {
|
||||
// host: "localhost", // 启动服务器域名
|
||||
// port: "3000", // 启动服务器端口号
|
||||
// open: true, // 是否自动打开浏览器
|
||||
// },
|
||||
mode: "production",
|
||||
devtool: "source-map",
|
||||
};
|
||||
```
|
||||
|
||||
## Image Minimizer
|
||||
|
||||
### 为什么
|
||||
|
||||
开发如果项目中引用了较多图片,那么图片体积会比较大,将来请求速度比较慢。
|
||||
|
||||
我们可以对图片进行压缩,减少图片体积。
|
||||
|
||||
**注意:如果项目中图片都是在线链接,那么就不需要了。本地项目静态图片才需要进行压缩。**
|
||||
|
||||
### 是什么
|
||||
|
||||
`image-minimizer-webpack-plugin`: 用来压缩图片的插件
|
||||
|
||||
### 怎么用
|
||||
|
||||
1. 下载包
|
||||
|
||||
```
|
||||
npm i image-minimizer-webpack-plugin imagemin -D
|
||||
```
|
||||
|
||||
还有剩下包需要下载,有两种模式:
|
||||
|
||||
- 无损压缩
|
||||
|
||||
```
|
||||
npm install imagemin-gifsicle imagemin-jpegtran imagemin-optipng imagemin-svgo -D
|
||||
```
|
||||
|
||||
- 有损压缩
|
||||
|
||||
```
|
||||
npm install imagemin-gifsicle imagemin-mozjpeg imagemin-pngquant imagemin-svgo -D
|
||||
```
|
||||
|
||||
> [有损/无损压缩的区别](https://baike.baidu.com/item/%E6%97%A0%E6%8D%9F%E3%80%81%E6%9C%89%E6%8D%9F%E5%8E%8B%E7%BC%A9)
|
||||
|
||||
2. 配置
|
||||
|
||||
我们以无损压缩配置为例:
|
||||
|
||||
```js{8,144-171}
|
||||
const os = require("os");
|
||||
const path = require("path");
|
||||
const ESLintWebpackPlugin = require("eslint-webpack-plugin");
|
||||
const HtmlWebpackPlugin = require("html-webpack-plugin");
|
||||
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
|
||||
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
|
||||
const TerserPlugin = require("terser-webpack-plugin");
|
||||
const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
|
||||
|
||||
// cpu核数
|
||||
const threads = os.cpus().length;
|
||||
|
||||
// 获取处理样式的Loaders
|
||||
const getStyleLoaders = (preProcessor) => {
|
||||
return [
|
||||
MiniCssExtractPlugin.loader,
|
||||
"css-loader",
|
||||
{
|
||||
loader: "postcss-loader",
|
||||
options: {
|
||||
postcssOptions: {
|
||||
plugins: [
|
||||
"postcss-preset-env", // 能解决大多数样式兼容性问题
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
preProcessor,
|
||||
].filter(Boolean);
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
entry: "./src/main.js",
|
||||
output: {
|
||||
path: path.resolve(__dirname, "../dist"), // 生产模式需要输出
|
||||
filename: "static/js/main.js", // 将 js 文件输出到 static/js 目录中
|
||||
clean: true,
|
||||
},
|
||||
module: {
|
||||
rules: [
|
||||
{
|
||||
oneOf: [
|
||||
{
|
||||
// 用来匹配 .css 结尾的文件
|
||||
test: /\.css$/,
|
||||
// use 数组里面 Loader 执行顺序是从右到左
|
||||
use: getStyleLoaders(),
|
||||
},
|
||||
{
|
||||
test: /\.less$/,
|
||||
use: getStyleLoaders("less-loader"),
|
||||
},
|
||||
{
|
||||
test: /\.s[ac]ss$/,
|
||||
use: getStyleLoaders("sass-loader"),
|
||||
},
|
||||
{
|
||||
test: /\.styl$/,
|
||||
use: getStyleLoaders("stylus-loader"),
|
||||
},
|
||||
{
|
||||
test: /\.(png|jpe?g|gif|svg)$/,
|
||||
type: "asset",
|
||||
parser: {
|
||||
dataUrlCondition: {
|
||||
maxSize: 10 * 1024, // 小于10kb的图片会被base64处理
|
||||
},
|
||||
},
|
||||
generator: {
|
||||
// 将图片文件输出到 static/imgs 目录中
|
||||
// 将图片文件命名 [hash:8][ext][query]
|
||||
// [hash:8]: hash值取8位
|
||||
// [ext]: 使用之前的文件扩展名
|
||||
// [query]: 添加之前的query参数
|
||||
filename: "static/imgs/[hash:8][ext][query]",
|
||||
},
|
||||
},
|
||||
{
|
||||
test: /\.(ttf|woff2?)$/,
|
||||
type: "asset/resource",
|
||||
generator: {
|
||||
filename: "static/media/[hash:8][ext][query]",
|
||||
},
|
||||
},
|
||||
{
|
||||
test: /\.js$/,
|
||||
// exclude: /node_modules/, // 排除node_modules代码不编译
|
||||
include: path.resolve(__dirname, "../src"), // 也可以用包含
|
||||
use: [
|
||||
{
|
||||
loader: "thread-loader", // 开启多进程
|
||||
options: {
|
||||
workers: threads, // 数量
|
||||
},
|
||||
},
|
||||
{
|
||||
loader: "babel-loader",
|
||||
options: {
|
||||
cacheDirectory: true, // 开启babel编译缓存
|
||||
cacheCompression: false, // 缓存文件不要压缩
|
||||
plugins: ["@babel/plugin-transform-runtime"], // 减少代码体积
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
plugins: [
|
||||
new ESLintWebpackPlugin({
|
||||
// 指定检查文件的根目录
|
||||
context: path.resolve(__dirname, "../src"),
|
||||
exclude: "node_modules", // 默认值
|
||||
cache: true, // 开启缓存
|
||||
// 缓存目录
|
||||
cacheLocation: path.resolve(
|
||||
__dirname,
|
||||
"../node_modules/.cache/.eslintcache"
|
||||
),
|
||||
threads, // 开启多进程
|
||||
}),
|
||||
new HtmlWebpackPlugin({
|
||||
// 以 public/index.html 为模板创建文件
|
||||
// 新的html文件有两个特点:1. 内容和源文件一致 2. 自动引入打包生成的js等资源
|
||||
template: path.resolve(__dirname, "../public/index.html"),
|
||||
}),
|
||||
// 提取css成单独文件
|
||||
new MiniCssExtractPlugin({
|
||||
// 定义输出文件名和目录
|
||||
filename: "static/css/main.css",
|
||||
}),
|
||||
// css压缩
|
||||
// new CssMinimizerPlugin(),
|
||||
],
|
||||
optimization: {
|
||||
minimizer: [
|
||||
// css压缩也可以写到optimization.minimizer里面,效果一样的
|
||||
new CssMinimizerPlugin(),
|
||||
// 当生产模式会默认开启TerserPlugin,但是我们需要进行其他配置,就要重新写了
|
||||
new TerserPlugin({
|
||||
parallel: threads, // 开启多进程
|
||||
}),
|
||||
// 压缩图片
|
||||
new ImageMinimizerPlugin({
|
||||
minimizer: {
|
||||
implementation: ImageMinimizerPlugin.imageminGenerate,
|
||||
options: {
|
||||
plugins: [
|
||||
["gifsicle", { interlaced: true }],
|
||||
["jpegtran", { progressive: true }],
|
||||
["optipng", { optimizationLevel: 5 }],
|
||||
[
|
||||
"svgo",
|
||||
{
|
||||
plugins: [
|
||||
"preset-default",
|
||||
"prefixIds",
|
||||
{
|
||||
name: "sortAttrs",
|
||||
params: {
|
||||
xmlnsOrder: "alphabetical",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
],
|
||||
},
|
||||
},
|
||||
}),
|
||||
],
|
||||
},
|
||||
// devServer: {
|
||||
// host: "localhost", // 启动服务器域名
|
||||
// port: "3000", // 启动服务器端口号
|
||||
// open: true, // 是否自动打开浏览器
|
||||
// },
|
||||
mode: "production",
|
||||
devtool: "source-map",
|
||||
};
|
||||
```
|
||||
|
||||
3. 打包时会出现报错:
|
||||
|
||||
```
|
||||
Error: Error with 'src\images\1.jpeg': '"C:\Users\86176\Desktop\webpack\webpack_code\node_modules\jpegtran-bin\vendor\jpegtran.exe"'
|
||||
Error with 'src\images\3.gif': spawn C:\Users\86176\Desktop\webpack\webpack_code\node_modules\optipng-bin\vendor\optipng.exe ENOENT
|
||||
```
|
||||
|
||||
我们需要安装两个文件到 node_modules 中才能解决, 文件可以从课件中找到:
|
||||
|
||||
- jpegtran.exe
|
||||
|
||||
需要复制到 `node_modules\jpegtran-bin\vendor` 下面
|
||||
|
||||
> [jpegtran 官网地址](http://jpegclub.org/jpegtran/)
|
||||
|
||||
- optipng.exe
|
||||
|
||||
需要复制到 `node_modules\optipng-bin\vendor` 下面
|
||||
|
||||
> [OptiPNG 官网地址](http://optipng.sourceforge.net/)
|
||||
|
||||
29
docs/senior/summary.md
Normal file
29
docs/senior/summary.md
Normal file
@@ -0,0 +1,29 @@
|
||||
# 总结
|
||||
|
||||
我们从 4 个角度对 webpack 和代码进行了优化:
|
||||
|
||||
1. 提升开发体验
|
||||
|
||||
- 使用 `Source Map` 让开发或上线时代码报错能有更加准确的错误提示。
|
||||
|
||||
2. 提升 webpack 提升打包构建速度
|
||||
|
||||
- 使用 `HotModuleReplacement` 让开发时只重新编译打包更新变化了的代码,不变的代码使用缓存,从而使更新速度更快。
|
||||
- 使用 `OneOf` 让资源文件一旦被某个 loader 处理了,就不会继续遍历了,打包速度更快。
|
||||
- 使用 `Include/Exclude` 排除或只检测某些文件,处理的文件更少,速度更快。
|
||||
- 使用 `Cache` 对 eslint 和 babel 处理的结果进行缓存,让第二次打包速度更快。
|
||||
- 使用 `Thead` 多进程处理 eslint 和 babel 任务,速度更快。(需要注意的是,进程启动通信都有开销的,要在比较多代码处理时使用才有效果)
|
||||
|
||||
3. 减少代码体积
|
||||
|
||||
- 使用 `Tree Shaking` 剔除了没有使用的多余代码,让代码体积更小。
|
||||
- 使用 `@babel/plugin-transform-runtime` 插件对 babel 进行处理,让辅助代码从中引入,而不是每个文件都生成辅助代码,从而体积更小。
|
||||
- 使用 `Image Minimizer` 对项目中图片进行压缩,体积更小,请求速度更快。(需要注意的是,如果项目中图片都是在线链接,那么就不需要了。本地项目静态图片才需要进行压缩。)
|
||||
|
||||
4. 优化代码运行性能
|
||||
|
||||
- 使用 `Code Split` 对代码进行分割成多个 js 文件,从而使单个文件体积更小,并行加载 js 速度更快。并通过 import 动态导入语法进行按需加载,从而达到需要使用时才加载该资源,不用时不加载资源。
|
||||
- 使用 `Preload / Prefetch` 对代码进行提前加载,等未来需要使用时就能直接使用,从而用户体验更好。
|
||||
- 使用 `Network Cache` 能对输出资源文件进行更好的命名,将来好做缓存,从而用户体验更好。
|
||||
- 使用 `Core-js` 对 js 进行兼容性处理,让我们代码能运行在低版本浏览器。
|
||||
- 使用 `PWA` 能让代码离线也能访问,从而提升用户体验。
|
||||
Reference in New Issue
Block a user