接下来JS除了把图片放到public文件夹之外,如何动态导入图片?

问题描述 投票:0回答:2

我正在制作一个教科书网站,每个作者都贡献一个教科书文件夹,其中包含一个 markdown 文件夹和一个图像文件夹:

textbooks
├───textbook-1
│   ├───images
│   └───markdown-files
└───textbook-2
    ├───images
    └───markdown-files

我将教科书文件夹存储在项目根文件夹中,并使用“fs”在构建时读取文件。到目前为止,我必须手动将图像文件夹放入公共文件夹中,以便在 Markdown 页面中使用它们。有没有办法动态导入这些图像文件而不将它们放入公共文件夹?

我正在使用 ReactMarkdown 来渲染 markdown,我正在考虑类似的事情:

<NextImage src={import(`../../textbooks/textbook-1/images/${imgFile}`)} />

但它不起作用...

javascript node.js next.js markdown
2个回答
0
投票

我见过的功能实践之一是将所有存储的图像放在一个集中的常量/*.ts中

import rectangle from "../assets/rectangle.svg";
import circle from "../assets/circle.svg";
import triangle from "../assets/triangle.svg";
import line from "../assets/line.svg";
import image from "../assets/image.svg";
import freeform from "../assets/freeform.svg";
import select from "../assets/select.svg";
import text from "../assets/text.svg";
import deleteIcon from "../assets/delete.svg";
import reset from "../assets/reset.svg";
import comments from "../assets/comments.svg";


export const shapeElements = [
  {
    icon: rectangle,
    name: "Rectangle",
    value: "rectangle",
  },
  {
    icon: circle,
    name: "Circle",
    value: "circle",
  },
  {
    icon: triangle,
    name: "Triangle",
    value: "triangle",
  },
  {
    icon: line,
    name: "Line",
    value: "line",
  },
  {
    icon: image,
    name: "Image",
    value: "image",
  },
  {
    icon: freeform,
    name: "Free Drawing",
    value: "freeform",
  },
];

export const navElements = [
  {
    icon: select,
    name: "Select",
    value: "select",
  },
  {
    icon: rectangle,
    name: "Rectangle",
    value: shapeElements,
  },
  {
    icon: text,
    value: "text",
    name: "Text",
  },
  {
    icon: deleteIcon,
    value: "delete",
    name: "Delete",
  },
  {
    icon: reset,
    value: "reset",
    name: "Reset",
  },
  {
    icon: comments,
    value: "comments",
    name: "Comments",
  },
];

然后使用常规 TS 导入来完成这项工作。

<Image
  src={shapeElements.find((el) => el.name === info?.name)?.icon}
  alt='Layer'
  width={16}
  height={16}
  className='group-hover:invert'
/>

如果像“assets/image/xxx.svg”这样的东西报告404,它就会起作用,因为Next.js想要从“_next/static”加载图像。希望有帮助


-4
投票

您需要导入图像,就像使用

Image
中的
next/image
组件导入其他模块一样。下面是来自 nextjs 文档的示例 next/image

import Image from 'next/image'
import profilePic from '../public/me.png'

function Home() {
  return (
    <>
      <h1>My Homepage</h1>
      <Image src={profilePic} alt="Picture of the author" />
      <p>Welcome to my homepage!</p>
    </>
  )
}

export default Home
© www.soinside.com 2019 - 2024. All rights reserved.