Mah*_*hdi 6 reactjs next.js nextjs-image
我使用 Next.jsImage组件进行图像优化。它在开发人员上工作得很好,但它不会从生产中的外部 URL 加载图像。
我能做什么?
小智 13
如果您想在 nextjs 应用程序中显示来自互联网的任何图像;这是我的下一个配置:
const nextConfig = {
reactStrictMode: true,
i18n,
sassOptions: {
includePaths: [path.join(__dirname, 'src/styles')],
prependData: `@import "variables.scss";`,
},
images: {
remotePatterns: [
{
protocol: 'https',
hostname: '**',
port: '',
pathname: '**',
},
],
},
}
Run Code Online (Sandbox Code Playgroud)
小智 8
例子:
在next.config.js
module.exports = {
images: {
domains: ['images.unsplash.com'],
},
}
Run Code Online (Sandbox Code Playgroud)
在页面/your_page_file.tsx
<Image
alt="The guitarist in the concert."
src="https://images.unsplash.com/photo-1464375117522-1311d6a5b81f?ixlib=rb-1.2.1&ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&auto=format&fit=crop&w=2250&q=80"
width={2250}
height={1390}
layout="responsive"
/>
Run Code Online (Sandbox Code Playgroud)
小智 7
在下一个配置中添加并声明您的域next.config.js:
module.exports = {
reactStrictMode: true,
images: {
domains: ["yourDomain.com"],
formats: ["image/webp"],
},
};Run Code Online (Sandbox Code Playgroud)
配置文件next.config.js应该位于项目的根目录中。
最后,即使在开发模式下也重新启动项目。
小智 6
为了供将来参考,我在将 next.js 站点部署到 Netlify 后遇到了同样的问题。只是后来,阅读我的日志,我发现
next.config.js 中设置的图像域将被忽略。请将环境变量 NEXT_IMAGE_ALLOWED_DOMAINS 设置为“cdn.sanity.io”
所以这可能是值得注意的事情。在我看到它之前,我将这个 next-sanity-image 插件https://www.sanity.io/plugins/next-sanity-image插入我的页面,这也绕过了问题
| 归档时间: |
|
| 查看次数: |
4534 次 |
| 最近记录: |