如何在NextJS中避免Image组件尺寸相关警告?
问题说明
你碰到的警告内容:
Image with src "http://localhost:3000/_next/static/media/icon_home.0f967506.svg" has either width or height modified, but not the other. If you use CSS to change the size of your image, also include the styles 'width: "auto"' or 'height: "auto"' to maintain the aspect ratio.
即便用了Next.js自动推断尺寸的写法,比如下面的代码,警告还是会出现:
<div className="flex aspect-square w-10 justify-center md:w-12"> <Image src={link.icon} alt={link.title} /> </div>
下面是几个不用手动指定图片尺寸就能消除警告的方法:
1. 给Image组件加自适应样式
添加width: auto和height: auto的内联样式,这不会固定图片尺寸,只是告诉Next.js保持宽高比,同时让图片继承父容器的尺寸限制:
<div className="flex aspect-square w-10 justify-center md:w-12"> <Image src={link.icon} alt={link.title} style={{ width: 'auto', height: 'auto' }} /> </div>
2. 用Tailwind类控制Image自适应
给Image组件加上w-full h-auto(或h-full w-auto)的Tailwind类,让它自适应父容器的大小,同时明确宽高的自适应规则,就能避开警告:
<div className="flex aspect-square w-10 justify-center md:w-12"> <Image src={link.icon} alt={link.title} className="w-full h-auto" /> </div>
3. 针对SVG图片的特殊处理
你示例里的是SVG格式,Next.js对SVG的自动尺寸推断偶尔会出问题。可以直接给SVG文件添加width和height属性,或者把SVG转成React组件导入使用,这样就能彻底避免尺寸相关的警告:
// 导入SVG为React组件 import IconHome from '../public/icon_home.svg'; <div className="flex aspect-square w-10 justify-center md:w-12"> <IconHome className="w-full h-auto" /> </div>
4. 临时禁用警告(不推荐)
如果上面的方法都不想用,可以在next.config.js里过滤这个警告,但这会隐藏所有同类提示,可能错过其他有用的错误信息,仅应急使用:
// next.config.js module.exports = { webpack: (config, { dev }) => { if (dev) { config.module.rules.push({ test: /\.js$/, enforce: 'pre', loader: 'eslint-loader', options: { ignoreWarnings: [warning => warning.message.includes('has either width or height modified') ] } }); } return config; } };
内容的提问来源于stack exchange,提问作者ssantos

