无法加载 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>
    );
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...