将 next/image 与 TypeScript 一起使用时,获取主机未配置错误

Lee*_*Lee 7 typescript next.js

我知道在不使用 TypeScript 的情况下使用 Next.js 图像组件时,需要在 中配置 URL next.config.js,但我不确定为什么这不适用于 TypeScript。

....,未在您的图像下配置next.config.js查看更多信息:https ://nextjs.org/docs/messages/next-image-unconfigured-host

解决方法是什么?或者是我使用常规img标签的唯一选择?

图像组件:

<Image
    src="https://images.unsplash.com/photo-1621794279356-0150106a4b45?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1"
    alt="blog title"
    width="100"
    height="100"
/> 
Run Code Online (Sandbox Code Playgroud)

next.config.ts

export const images = {
  domains: [
    "images.unsplash.com"
  ],
};
Run Code Online (Sandbox Code Playgroud)

jul*_*ves 10

Next.js 最终会查找一个next.config.js文件来获取配置(如果您使用的是 ,则很可能没有该文件next.config.ts)。

您可以将.ts配置编译为.js配置,或者只是创建一个next.config.js文件。

// next.config.js
module.exports = {
    images: {
        domains: ['images.unsplash.com']
    }
}
Run Code Online (Sandbox Code Playgroud)

从 Next.js 12 开始,您现在可以通过将配置文件重命名为next.config.mjs. 虽然这与使用 TypeScript 并不完全相同,但至少可以保持语法一致。

// next.config.mjs
export default {
    images: {
        domains: ['images.unsplash.com']
    }
}
Run Code Online (Sandbox Code Playgroud)


Mic*_*ung 0

我认为你应该更好地用于next.config.js配置下一个而不是next.config.ts在打字稿项目中。这应该是.js.

如果你坚持使用next.config.ts,可以参考这个问题

但同样,有些可能会减慢启动时间,有些仍然需要您next.config.jsnext.config.ts