首页 > 解决方案 > 无法加载 PNG 图片 | NextJS

问题描述

我有一个网站以我使用 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解决这个问题,但没有成功。

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

标签: reactjsimagewebpacknext.js

解决方案


由于您的图片位于public文件夹中,并且为了避免加载图像文件的额外配置,您可以简单地通过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>
    );
}

查看静态文件服务了解更多详情。


推荐阅读