我有一个网站,以图库格式提供照片,这些照片是我使用 Next.js 创建的。我将所有图像存储在 /public/photos/
中,并分组到子文件夹中,并将它们导入到需要的位置(见下文)。
主页由带有照片背景和标题的各个图 block (图 block 组件)的网格(图 block 组件)组成。照片导入到 tiles.tsx
中,并作为 Prop 传递到 tile
组件,这样我就可以轻松添加更多图 block 。
当我使用 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 图像上,jpeg 和 jpg 不会造成问题。我尝试用 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>
);
}
查看Static File Serving了解更多详情。
关于reactjs - 无法加载PNG图像|下一个JS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67153903/