我正在用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/文件夹中。
我有两个文件夹:blog/ & tutorials/
每个帖子都在blog/或tutorials/中各自的文件夹中&每个文件夹都包含特定帖子中使用的图像。
例如,在hello-world文件夹中,有一个名为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文件使用通过hydrate传递的上述Image组件。
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/文件夹中包含它的图像一样。
发布于 2020-09-18 22:17:49
不幸的是,这是不可能的,因为next-mdx-remote将markdown内容视为数据&根本不会通过Webpack传递:(
https://stackoverflow.com/questions/63957018
复制相似问题