5

So, I'm trying to display pure markdown in my NextJS Typescript page, I tried it:

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

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

export default Post1;

But I got it:

./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

I already created the markdown.d.ts file

Obs.: I don't want to convert md to jsx, just want to display it, I already did it in this gist

5
  • Possible duplicate of stackoverflow.com/questions/42928530/… Commented Oct 4, 2022 at 19:50
  • @Sovari no, a don't want to convert the markdown, just show it purely Commented Oct 4, 2022 at 20:00
  • if you needn't format md file, just use <pre>{markdown}</pre> Commented Oct 4, 2022 at 20:08
  • @DaniilLoban same error Commented Oct 4, 2022 at 20:19
  • Possible duplicate of stackoverflow.com/questions/47954367/… Commented Oct 4, 2022 at 21:10

2 Answers 2

3

Oh now I get it. You could try this then:

return <>{JSON.stringify(markdown, 2, null)}</>;
Sign up to request clarification or add additional context in comments.

5 Comments

imgur.com/LrkWMKM and same error
You'll probably need to incorporate a markdown-loader into your webpack config first npmjs.com/package/markdown-loader
And here's how you extend your webpack config with an additional loader nextjs.org/docs/api-reference/next.config.js/…
TYYYYY I WANNA KISS YOU
I'm so happy it helped you!
2

My approach:

  1. Install markdown parsing library (react-markdown or other, I will use marked)

  2. Place your markdown_file.md file in /public folder

  3. Read file on the server /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>
    );
}

const filePath = join(process.cwd(), 'public', 'markdown_file.md');

export async function getStaticProps() {
    const fileContent = fs.readFileSync(filePath, 'utf8');
    return {
        props: {
            html: marked.parse(fileContent),
        },
    };
}

1 Comment

const { join } = require('path'); const fs = require('fs');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.