微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

无法加载 PNG 图片 |下一个JS

如何解决无法加载 PNG 图片 |下一个JS

我有一个使用 Next.js 创建的以图库格式提供照片的网站。我将存储在 /public/photos/ 中的所有图像分组到子文件夹中,并将它们导入到需要的地方(见下文)。

主页由带有照片背景和标题的单个图块(图块组件)的网格(图块组件)组成。照片被导入到 tiles.tsx 并作为道具传递给 tile 组件,因此我可以轻松添加更多图块。

当我用 npm run dev 编译这个项目时,我得到这个错误

error - ./public/photos/astro/astro.png
Module parse Failed: Unexpected character '�' (1:0)
You may need an appropriate loader to handle this file type,currently no loaders are configured to process this file.

我的 webpack 配置如下:

const webpack = require('webpack');
const path = require('path');

module.exports = {
    module: {
      rules: [
        {
          test: /\.(png|jpe?g|gif)$/i,use: [
            {
              loader: 'file-loader',},],}
};

tiles.tsx 如下:

import React from "react";
import Tile from "./tile";
import styles from "@styles/tiles.module.css";


import landscape from "../public/photos/landscape/landscape.png";
import astro from "../public/photos/astro/astro.png";
import cgi from "../public/photos/cg/cg.png";
import flowers from "../public/photos/flowers/flowers.png";

function Tiles() {
    return(
        <div>
            <div className={styles.gallery}>
                <Tile title="Landscape" photo={landscape} location="landscape"/>
                <Tile title="Astro" photo={astro} location="astro"/>
                <Tile title='CGI' photo={cgi} location="cgi"/>
                <Tile title="Flowers" photo={flowers} location="flowers"/>
            </div>
        </div>
    );
}

export default Tiles;

tile.tsx 如下:

import styles from '@styles/tile.module.css'

const Tile = (props) => {
    return(
        <div>
            <a className={styles.linkWrapper} href={props.location}>
                <div className={styles.imageContainer}>
                        <img className={styles.image} src={props.photo}/>
                    <div className={styles.title}>{props.title}</div>
                </div>
            </a>
        </div>
    );
}

export default Tile;

我相信我已经正确配置了我的 webpack 来加载这些文件。此错误仅发生在 png 图像上,jpegs 和 jpgs 没有问题。我曾尝试使用 next-images 解决此问题,但未成功。

如有任何帮助,请提供帮助。如果需要,我很乐意提供额外的代码

解决方法

由于您的图片位于 public 文件夹中,并且为了避免添加额外的配置以通过代码加载图像文件,您可以简单地通过从基本 URL 开始的文件夹中的路径引用每个图像( /).

function Tiles() {
    return(
        <div>
            <div className={styles.gallery}>
                <Tile title="Landscape" photo="/photos/landscape/landscape.png" location="landscape"/>
                <Tile title="Astro" photo="/photos/astro/astro.png" location="astro"/>
                <Tile title='CGI' photo="/photos/cg/cg.png" location="cgi"/>
                <Tile title="Flowers" photo="/photos/flowers/flowers.png" location="flowers"/>
            </div>
        </div>
    );
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。