您可以将 gulpfile 与gulp-responsive
或一起使用gulp-sharp-responsive
。我个人使用后者,因为它支持AVIF
格式。
要将它与您的 Angular 项目很好地集成,您可以按照以下步骤操作:
- 安装依赖项:
npm i --save-dev gulp gulp-sharp-responsive
gulpfile.js
使用以下内容在项目根目录中创建
const { src, dest } = require("gulp");
const sharpResponsive = require("gulp-sharp-responsive");
const compress = () =>
src("images/*.{png,jpg}")
.pipe(
sharpResponsive({
formats: [
// jpeg
{ width: 256, format: "jpeg", rename: { suffix: "-256" } },
{ width: 512, format: "jpeg", rename: { suffix: "-512" } },
{ width: 1024, format: "jpeg", rename: { suffix: "-1024" } },
// webp
{ width: 256, format: "webp", rename: { suffix: "-256" } },
{ width: 512, format: "webp", rename: { suffix: "-512" } },
{ width: 1024, format: "webp", rename: { suffix: "-1024" } },
// avif
{ width: 256, format: "avif", rename: { suffix: "-256" } },
{ width: 512, format: "avif", rename: { suffix: "-512" } },
{ width: 1024, format: "avif", rename: { suffix: "-1024" } },
],
})
)
.pipe(dest("src/assets/compressed"));
module.exports = {
compress,
};
- 在您的项目根目录中创建一个文件夹,您的未压缩图像文件所在的位置(在此示例中称为
images
)
- 将预安装脚本添加到您的
package.js
.,以便在每次构建时调用您的 gulpfile
"scripts": {
"prebuild": "gulp compress",
// ...
},
如果您npm run build
现在调用,它会在实际运行之前压缩您的图像并将它们移动到指定的资产文件夹中ng build
。
现在您可以使用带有picture
/source
组合的图像文件,如下面的代码片段所示。请记住,源标签的顺序很重要。
<!-- {{image}} is the image name -->
<picture *ngIf="image">
<!-- avif -->
<source
srcset="assets/compressed/{{image}}-256.avif"
media="(max-width: 512px)"
type="image/avif"
/>
<source
srcset="assets/compressed/{{image}}-512.avif"
media="(max-width: 1024px)"
type="image/avif"
/>
<source
srcset="assets/compressed/{{image}}-1024.avif"
media="(max-width: 2048px)"
type="image/avif"
/>
<!-- webp -->
<source
srcset="assets/compressed/{{image}}-256.webp"
media="(max-width: 512px)"
type="image/webp"
/>
<source
srcset="assets/compressed/{{image}}-512.webp"
media="(max-width: 1024px)"
type="image/webp"
/>
<source
srcset="assets/compressed/{{image}}-1024.webp"
media="(max-width: 2048px)"
type="image/webp"
/>
<!-- jpeg -->
<source
srcset="assets/compressed/{{image}}-256.jpg"
media="(max-width: 512px)"
type="image/jpeg"
/>
<source
srcset="assets/compressed/{{image}}-512.jpg"
media="(max-width: 1024px)"
type="image/jpeg"
/>
<source
srcset="assets/compressed/{{image}}-1024.jpg"
media="(max-width: 2048px)"
type="image/jpeg"
/>
<!-- original -->
<img src="assets/compressed/{{ image }}-1024.jpg" />
</picture>