【问题标题】:Getting host is not configured error when using next/image with TypeScript使用带有 TypeScript 的 next/image 时获取主机未配置错误
【发布时间】:2021-08-12 06:32:11
【问题描述】:

我知道在不使用 TypeScript 的情况下使用 Next.js 图像组件时,需要在 next.config.js 中配置 URL,但我不确定为什么这不适用于 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"
/> 

next.config.ts

export const images = {
  domains: [
    "images.unsplash.com"
  ],
};

【问题讨论】:

    标签: typescript next.js


    【解决方案1】:

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

    要么将 .ts 配置编译为 .js 配置,要么直接创建 next.config.js 文件。

    // next.config.js
    module.exports = {
        images: {
            domains: ['images.unsplash.com']
        }
    }
    

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

    // next.config.mjs
    export default {
        images: {
            domains: ['images.unsplash.com']
        }
    }
    

    【讨论】:

      【解决方案2】:

      我认为您最好在 typescript 项目中使用 next.config.js 来配置 next 而不是 next.config.ts。这应该是.js 中唯一的文件。

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

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

      【讨论】:

        猜你喜欢
        • 2021-09-13
        • 2021-04-11
        • 1970-01-01
        • 2021-03-02
        • 2021-11-17
        • 2021-06-06
        • 1970-01-01
        • 2022-08-16
        • 1970-01-01
        相关资源
        最近更新 更多