【发布时间】:2022-01-30 23:22:36
【问题描述】:
我正在使用next-mdx-remote 制作博客,并且想使用public/ 文件夹之外的.mdx 文件中的图像。
这是我的博客项目的完整代码→https://github.com/deadcoder0904/blog-mdx-remote
我有以下文件夹结构:
.
├── package-lock.json
├── package.json
├── pages
│ ├── _app.js
│ ├── blog
│ │ └── [slug].js
│ ├── dark.css
│ ├── index.js
│ └── new.css
├── posts
│ ├── blog
│ │ ├── hello-world
│ │ │ ├── Rustin_Cohle.jpg
│ │ │ └── index.mdx
│ │ └── shit-world
│ │ └── index.mdx
│ └── tutorials
│ └── console-log-in-javascript
│ └── index.mdx
└── utils
└── mdxUtils.js
我的所有内容都在posts/ 文件夹中。
我有 2 个文件夹:blog/ & tutorials/
每个帖子都位于blog/ 或tutorials/ 内的自己的文件夹中,并且每个文件夹都包含在该特定帖子中使用的图像。
例如hello-world文件夹中有1张图片名为Rustin_Cohle.jpg。
我想在hello-world/index.mdx 文件中使用这张图片,但我做不到。
我不能使用import 或require,因为这是next-mdx-remote 的限制。
我尝试使用名为 Image 的自定义组件,它在下面使用 img 并将其传递给 hydrate,但它也不起作用。
组件/Image.js
export const Image = ({ src, alt }) => (
<img style={{ backgroundColor: 'red' }} src={src} alt={alt} />
)
pages/blog/[slug].js
import hydrate from 'next-mdx-remote/hydrate'
import { Image } from '../components/Image'
const components = { Image }
const Blog = ({ source, frontMatter }) => {
const content = hydrate(source, { components })
return (
<div>
<h1>{frontMatter.title}</h1>
{content}
</div>
)
}
以下 MDX 文件使用上述 Image 组件作为通过 hydrate 传递。
hello-world/index.mdx
---
title: Hello World
date: '2019-09-06T14:54:37.229Z'
tags: ['hello', 'world']
author: John Doe
description: This is the first post
---
Hey this is my first post

<img src="./Rustin_Cohle.jpg" alt="Rust Cohle" />
<Image src="./Rustin_Cohle.jpg" alt="Rust Cohle" />
This is the end of the first post
我什至尝试过使用MDXProvider,但也没有用。
pages/index.js
import { MDXProvider } from '@mdx-js/react'
const components = { Image }
const HomePage = ({ posts }) => {
return (
<MDXProvider components={components}>
...
</MDXProvider>
)
}
那我该如何使用图片呢?我希望它们仅位于特定帖子的文件夹中,例如 hello-world 博客将仅在 hello-world/ 文件夹中包含其图像。
【问题讨论】:
-
如果您使用的是
mdx-bundler,请查看following answer。
标签: javascript reactjs next.js mdxjs