[英]Webpack5 how to minimize copying assets such as images
我有以下webpack.config.js文件,從這個配置我設法壓縮了從 css 文件中使用的所有圖像。
但我也想壓縮我正在復制到 dist 文件夾中的所有圖像。
const CopyPlugin = require("copy-webpack-plugin");
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
use: ['style-loader', 'css-loader'],
},
{
test: /\.(gif|png|jpe?g|svg)$/i,
use: [
'file-loader',
{
loader: 'image-webpack-loader',
options: {
mozjpeg: {
progressive: true,
},
// optipng.enabled: false will disable optipng
optipng: {
enabled: false,
},
pngquant: {
quality: [0.65, 0.90],
speed: 4
},
gifsicle: {
interlaced: false,
},
// the webp option will enable WEBP
webp: {
quality: 75
}
}
},
],
}
],
},
plugins: [
// copying static assets to dist directory, i want these images to be compressed as well
new CopyPlugin({
patterns: [{
from: "source/images",
to: "images"
}
],
})
]};
我怎樣才能在 webpack 5 中實現這一點?
我看到這篇不錯的文章 ( https://web.dev/codelab-imagemin-webpack/ ) 解釋了如何實現這一點,但似乎 imagemin-webpack-plugin 最近沒有更新。
我能夠通過將copy-webpack-plugin
與image-minimizer-webpack-plugin
最小化器一起使用來實現這一點。 我的配置看起來像這樣。
const CopyPlugin = require("copy-webpack-plugin");
const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
module.exports = {
plugins: [
new CopyPlugin({
patterns: [
{
from: 'path/to/images/*',
to({ context, absoluteFilename }) {
return "dest/[name][ext]";
}
},
],
}),
],
optimization: {
minimizer: [
new ImageMinimizerPlugin({
loader: true,
minimizer: {
implementation: ImageMinimizerPlugin.imageminMinify,
options: {
plugins: [
"imagemin-gifsicle",
"imagemin-mozjpeg",
"imagemin-pngquant",
"imagemin-svgo",
],
},
},
generator: [
{
type: "asset",
implementation: ImageMinimizerPlugin.imageminGenerate,
options: {
plugins: [
"imagemin-gifsicle",
"imagemin-mozjpeg",
"imagemin-pngquant",
"imagemin-svgo",
],
},
},
],
}),
],
},
}
這部分文檔使我找到了這個解決方案。 https://webpack.js.org/plugins/image-minimizer-webpack-plugin/#generate-webp-images-from-copied-assets
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.