reactjs - 无法加载 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解决这个问题,但没有成功。
如果赞赏,请提供任何帮助。如有必要,我很乐意提供额外的代码。
解决方案
由于您的图片位于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>
);
}
查看静态文件服务了解更多详情。
推荐阅读
- c# - 用于替换值的 REGEX 帮助
- c# - 如何调用返回列表的存储过程
使用 .net 核心实体框架 - embedded - USART中idle和break字符的目的是什么?
- javascript - 在 Apollo Express GraphQL 中出现错误:错误:模式必须包含唯一命名的类型,但包含多个名为“DateTime”的类型
- python - How to Write a Cleaner and performant code with Pandas while reading CSV
- apache-kafka - KSQL 无法加入加入的流,ksql 中的菊花链
- android - Firebase 评论查看错误 - 反序列化时需要一个列表,但有一个类 java.util.HashMap
- asp.net - 从 Postman API 调用重定向到 Web UI
- html - 为什么页脚在顺风 css 中浮动
- python - 如何根据页码将单个 pdf 拆分为多个 PdfFileReader 对象?