[英]Webpack5 how to minimize copying assets such as images
I have following webpack.config.js file, from this configuration I managed to compress all images which are consumed from css files.我有以下webpack.config.js文件,从这个配置我设法压缩了从 css 文件中使用的所有图像。
But I also want to compress all images which I'm copying into dist folder.但我也想压缩我正在复制到 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"
}
],
})
]};
How can I achieve this in webpack 5?我怎样才能在 webpack 5 中实现这一点?
I saw this nice article ( https://web.dev/codelab-imagemin-webpack/ ) explaining how this can be achieved but as it seems imagemin-webpack-plugin is not updated recently.我看到这篇不错的文章 ( https://web.dev/codelab-imagemin-webpack/ ) 解释了如何实现这一点,但似乎 imagemin-webpack-plugin 最近没有更新。
I was able to get this working by using the copy-webpack-plugin
with image-minimizer-webpack-plugin
minimizer.我能够通过将copy-webpack-plugin
与image-minimizer-webpack-plugin
最小化器一起使用来实现这一点。 My config looks something like this.我的配置看起来像这样。
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",
],
},
},
],
}),
],
},
}
This portion of the docs led me to this solution.这部分文档使我找到了这个解决方案。 https://webpack.js.org/plugins/image-minimizer-webpack-plugin/#generate-webp-images-from-copied-assets https://webpack.js.org/plugins/image-minimizer-webpack-plugin/#generate-webp-images-from-copied-assets
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.