【问题标题】:NextJS Image Component and Image Optimization is not workingNextJS 图像组件和图像优化不起作用
【发布时间】:2021-02-21 10:06:35
【问题描述】:

我是 NextJS 的新手。我刚刚在 NextJS 文档中看到了这个新的图像优化功能,但它对我不起作用。

这是我的代码。代码中指定了有效的部分和无效的部分。

import Image from "next/image";

interface sponsorsProps {}

const Sponsors: React.FC<sponsorsProps> = ({}) => {
  return (
    <section className="bg-img-with-opacity2 pt-10">
      <div className="container text-gray-400">
        <div className="flex justify-center items-center">
          <h2 className="text-4xl font-bold">Our Verified Sponsors</h2>
        </div>

        <div className="grid grid-cols-4 gap-5">
          {images &&
            images.map((img) => {
              return (
                <div className="p-5 mt-5 text-center" key={img.img}>
                  <div className="flex justify-center items-center mb-4">
                      {/* This doesn't work */}
                    <Image
                      src={img.img}
                      alt="provider image"
                      width={500}
                      height={500}
                    ></Image>
                    {/* This works */}
                    <img
                      src={img.img}
                      className="bg-mint text-mint fill-current"
                      alt="provider image"
                    />
                  </div>
                </div>
              );
            })}
        </div>
      </div>
    </section>
  );
};

const images = [
  {
    img: "/images/bkash.png",
  },
  {
    img: "/images/nogod.png",
  },
  {
    img: "/images/rocket.png",
  },
  {
    img: "/images/sure_cash_logo.png",
  },
];

export default Sponsors;

我得到的错误是这样的:

images:1 GET http://localhost:3000/images?url=%2Fimages%2Frocket.png&w=640&q=75 404 (Not Found)

谁能帮我解决这个问题?

【问题讨论】:

  • 图片文件在哪个文件夹?
  • 公共文件夹。在那里我有一个图像文件夹,图像在该文件夹内。您可以在 images 数组中指定的代码中看到。

标签: image next.js nextjs-image


【解决方案1】:

您必须在 next.config.js 文件中配置图像路径,如下所示,这不是必需的:

module.exports = {
  images: {
    domains: ["localhost"],
    // next line is not required
    path: 'http://localhost:3000/images'
  }
};

除非你有第三方图片提供者,否则不需要配置路径属性,参见文档here

【讨论】:

  • 但我从未创建过配置文件
  • @PRANTADutta 这很奇怪,我尝试了这个配置并得到了同样的错误,所以我认为这可能是问题所在。你能在沙盒中重现这个问题吗?帮助会更容易:)
  • 我尝试在沙盒中创建此问题。但它可以工作,但它不能在我的电脑上工作。 WTF ......
【解决方案2】:

如果将图像放在 /public 文件夹的根目录中,它会起作用吗? (而不是 /public/images)

【讨论】:

  • 不,它没有。抱歉回复晚了。
猜你喜欢
  • 2022-12-30
  • 2022-10-01
  • 2023-01-31
  • 2021-06-20
  • 1970-01-01
  • 1970-01-01
  • 2020-07-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多