nextjs typescript图像加载器

8gsdolmq  于 5个月前  发布在  TypeScript
关注(0)|答案(1)|浏览(57)

我正在用NEXT.js typescript建立一个网站。我是一个typescript新手。
我需要制作ImageLoader,因为cloudflare页面不支持默认的图像加载器。但我的代码不工作,我不知道为什么。
装载机代码:

const normalizeSrc = (src: string) => {
  return src.startsWith("/") ? src.slice(1) : src;
};

const cloudflareLoader = ({
  src,
  width,
  quality,
}: {
  src: string;
  width: number;
  quality: number;
}) => {
  const params = [`width=${width}`];
  if (quality) {
    params.push(`quality=${quality}`);
  }

  const paramsString = params.join(".");
  return `/cdn-cgi/images/${paramsString}/${normalizeSrc(src)}`;
};

字符串
图片编码:

<Image
  loader={cloudflareLoader}
  src="/images/image-name.png" // image in public/images folder
  height={120}
  width={120}
  alt=""
/>


错误类型:

Type '({ src, width, quality, }: { src: string; width: number; quality: number; }) => string' is not assignable to type 'ImageLoader'.
  Types of parameters '__0' and 'p' are incompatible.
    Type 'ImageLoaderProps' is not assignable to type '{ src: string; width: number; quality: number; }'.
      Types of property 'quality' are incompatible.
        Type 'number | undefined' is not assignable to type 'number'.
          Type 'undefined' is not assignable to type 'number'.


我该怎么办?
我指的是https://developers.cloudflare.com/images/image-resizing/integration-with-frameworks/

nwlqm0z1

nwlqm0z11#

next/image中删除类型定义将确保您不会创建自己的类型,使用next中的类型更安全,因为您总是知道它是next所期望的。
你可以这样做:

import type { ImageLoaderProps } from 'next/image';

export default function imageLoader({ src, width, quality }: ImageLoaderProps) {...}

字符串
您的代码示例将变成这样:

import type { ImageLoaderProps } from 'next/image';

const normalizeSrc = (src: string) => {
  return src.startsWith('/') ? src.slice(1) : src;
};

const cloudflareLoader = ({ src, width, quality }: ImageLoaderProps) => {
  const params = [`width=${width}`];
  if (quality) {
    params.push(`quality=${quality}`);
  }

  const paramsString = params.join('.');
  return `/cdn-cgi/images/${paramsString}/${normalizeSrc(src)}`;
};

相关问题