Webpack5 教程减少页面体积
本文目录
减少页面体积
开发时我们定义了一些工具函数库,或者引用第三方工具函数库或组件库。
如果没有特殊处理的话我们打包时会引入整个库,但是实际上可能我们可能只用上极小部分的功能。
这样将整个库都打包进来,体积就太大了。
Webpack 已经默认开启了这个功能,无需其他配置
优化Babel
Babel 对一些公共方法使用了非常小的辅助代码,比如 _extend。默认情况下会被添加到每一个需要它的文件中。
你可以将这些辅助代码作为一个独立模块,来避免重复引入。
- @babel/plugin-transform-runtime: 禁用了 Babel 自动对每个文件的 runtime 注入,而是引入
- @babel/plugin-transform-runtime 并且使所有辅助代码从这里引用
依赖包
npm i @babel/plugin-transform-runtime -D
修改配置
{
test: /\.js$/,
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"], // 减少代码体积
},
}
],
},
整个
const os = require("os");
const path = require("path");
const ESLintPlugin = 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;
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: {
//输出路径
//__dirname nodejs的变量,代表当前文件所在的文件夹目录
path: path.resolve(__dirname, "../dist"), //绝对路径
//入口文件输出文件名
filename: "static/js/index.js",
clean: true, //自动清空上次打包的内容,原理,将path目录清空,再进行打包
},
//加载器
module: {
rules: [{
oneOf: [
//loader配置
{
test: /\.css$/i,
use: getStyleLoaders(),
},
{
test: /\.less$/i,
//loader:'xx' 只能使用1个loader
use: getStyleLoaders('less-loader'),
},
{
test: /\.s[ac]ss$/i,
use: getStyleLoaders('sass-loader'),
},
{
test: /\.styl$/,
loader: "stylus-loader", // 将 Stylus 文件编译为 CSS
},
{
test: /\.(png|jp?g|gif|webp|svg)$/,
type: "asset",
parser: {
dataUrlCondition: {
//小于10kb的图片转base64
//有点,减少请求数量,缺点,体积会变大
maxSize: 10 * 1024
}
},
generator: {
//hash:10 表示取hash前10位
filename: 'static/img/[hash:10][ext][query]'
}
},
//图标设置
{
test: /\.(ttf|woff2?)$/,
type: "asset/resource",
generator: {
//hash:10 表示取hash前10位
filename: 'static/font/[hash:10][ext][query]'
}
},
//视频文件
{
test: /\.(mp3|avi|mp4)$/,
type: "asset/resource",
generator: {
//hash:10 表示取hash前10位
filename: 'static/video/[hash:10][ext][query]'
}
},
//处理转换es6
{
test: /\.js$/,
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 ESLintPlugin({
//检查目录下的文件
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",
}),
],
optimization: {
minimize: true,
minimizer: [
// css压缩也可以写到optimization.minimizer里面,效果一样的
new CssMinimizerPlugin(),
// 当生产模式会默认开启TerserPlugin,但是我们需要进行其他配置,就要重新写了
new TerserPlugin({
parallel: threads // 开启多进程
})
],
},
//模式
mode: "production",
devtool: "source-map",
}
图片压缩
开发如果项目中引用了较多图片,那么图片体积会比较大,将来请求速度比较慢。
我们可以对图片进行压缩,减少图片体积。
注意:如果项目中图片都是在线链接,那么就不需要了。本地项目静态图片才需要进行压缩。
依赖包
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
配置
const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
...
module.exports = {
optimization: {
minimize: true,
minimizer: [
...
// 压缩图片
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",
},
},
],
},
],
],
},
},
}),
],
},
}
可能存在下载包失败问题,如果下载不来,等过段时间再试。
打包时会出现报错:
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
下载
- jpegtran.exe
需要复制到 node_modules\jpegtran-bin\vendor 下面
- OptiPNG 官网地址
https://optipng.sourceforge.net/
需要复制到 node_modules\optipng-bin\vendor 下面
版权提示
1.除了标识原创之外,其他可能来源于网友的分享,仅供学习使用2.如您发现侵犯了您的权利,请联系我们删除
3.转载必须带本文链接,否则你将侵权
4.关于会员或其发布的相关内容均由会员自行提供,会员依法应对其提供的任何信息承担全部责任,本站不对此承担任何法律责任
评论区 (0)
没有记录
请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!