reactjs 如何在NextJS中导入markdown文件

iq0todco  于 2023-04-29  发布在  React
关注(0)|答案(2)|浏览(207)

所以,我试图在我的NextJS Typescript页面中显示纯markdown,我试过了:

import React, { useState, useEffect } from "react";
import markdown from "./assets/1.md";

const Post1 = () => {
  return <>{markdown}</>;
};

export default Post1;

但我明白了

./pages/blog/assets/1.md
Module parse failed: Unexpected character ' ' (1:1)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
> # Apresentations
| 
| Hi, my name is Vitor Koch

我已经创建了Markdown。d.ts文件

观察结果:我不想把md转换成jsx,只是想把它显示出来,我已经在this gist中做了

wnavrhmk

wnavrhmk1#

现在我懂了你可以试试这个:

return <>{JSON.stringify(markdown, 2, null)}</>;
x7rlezfr

x7rlezfr2#

我的方法:
1.安装markdown解析库(react-markdown或其他,我将使用marked
1.将您的markdown_file.md文件放在/public文件夹中
1.获取服务器/pages/your_page.tsx上的文件:

import React from 'react';
import { marked } from 'marked';

export default function YourPage(props: { html: string }) {
    const { html } = props;
    return (
        <div>
            <span dangerouslySetInnerHTML={{ __html: html }} />
        </div>
    );
}

export async function getStaticProps() {
    const response = await fetch(`${process.env.MAIN_ORIGIN}/markdown_file.md`);
    const markdown = await response.text();

    return {
        props: {
            html: marked.parse(markdown),
        },
        revalidate: 24 * 60 * 60, // Adds static caching with cleanup every 24 hours
    };
}

需要MAIN_ORIGINgetStaticProps只支持绝对URL。

相关问题