面试题答案
一键面试1. 安装 next - image
库
Next.js 提供了 next - image
库来优化图像。在项目目录下运行以下命令进行安装:
npm install next - image
或
yarn add next - image
2. 导入和使用 Image
组件
在你的 React 组件中,导入 Image
组件并使用它来替换原生的 <img>
标签。例如:
import Image from 'next/image';
function MyComponent() {
return (
<div>
<Image
src="/path/to/your/image.jpg"
alt="description of the image"
width={500}
height={300}
/>
</div>
);
}
export default MyComponent;
3. 配置 next.config.js
在项目根目录的 next.config.js
文件中,进行如下配置:
module.exports = {
images: {
domains: ['your - image - domain.com'], // 如果图像来自外部域名,需要在此指定域名
deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840], // 定义不同设备宽度下的图像尺寸
imageSizes: [16, 32, 48, 64, 96, 128, 256, 384], // 定义生成的图像占位符尺寸
minimumCacheTTL: 60 * 60 * 24 * 365, // 图像缓存时间(秒),这里设置为1年
},
};
4. 图像优化原理及优势
- 自动格式转换:
next - image
会根据浏览器支持情况,自动将图像转换为最佳格式(如 WebP),通常 WebP 格式比 JPEG 或 PNG 有更好的压缩率,从而减小文件大小。 - 响应式加载:根据设备屏幕尺寸和视口大小,加载合适尺寸的图像,避免加载过大图像造成带宽浪费,提升加载速度。
- 占位符:
next - image
支持生成低质量的图像占位符(LQIP),在图像加载过程中先显示占位符,提升用户体验。