React 无法导入图像,图像“不是有效的图像文件”

问题描述 投票:0回答:3

我正在尝试编译一个包含一些图像的项目。当我使用yarn dev时,我可以编译几乎所有内容,但是当涉及到图像时,它总是会给我以下错误:

Error: Image import "../assets/images/banner-moc-1-1.png" is not a valid image file. The image may be corrupted or an unsupported format.

我不明白为什么它这么说,因为我的文件是经典的 png。我不认为问题出在图像上。

我错过了什么吗?

我正在使用下一个模板。构建时出现问题,发生类型错误。我已将 packages.json 中的每个包更新到最新版本,认为它可以工作。现在它可以编译了,但它给了我您在上面读到的错误消息。

reactjs image import next.js
3个回答
0
投票

我遇到了同样的问题,并通过将路径放入图像 src 属性 (

<Image src='/some-path' />
) 来解决它,删除所有图像导入 (
import SomeImage from 'some-path'
)


0
投票

我找到了一个适合我的 nextjs 配置:

// @generated: @expo/[email protected]
// Learn more: https://docs.expo.io/guides/using-nextjs/

const { withExpo } = require("@expo/next-adapter");
const withPlugins = require("next-compose-plugins");
const withImages = require("next-images");
const withFonts = require("next-fonts");
const withTM = require("next-transpile-modules")(["react-native-web"]);

const nextConfig = {
  images: {
    disableStaticImages: true,
  },
};

module.exports = withPlugins(
  [withTM, withExpo, withImages, withFonts],
  nextConfig
);

这是我的github问题

在这里我找到了答案(史蒂文·马修斯)

注意:这是我的 React Native Web + nextjs 项目。应该可以,但如果不行我不知道该怎么办


0
投票

将其添加到您的 nextjs 配置中。 如果您想从其他网站导入图片用于开发目的,您还可以指定

remotePatterns
,否则会出现错误。

const nextConfig = {
  reactStrictMode: false,
  images: {
    formats: ['image/webp'],
    remotePatterns: [
      {
        protocol: 'https',
        hostname: '**',
        port: '',
        pathname: '**',
      },
    ],
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.