Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import markdown files dynamically with Vite

Tags:

reactjs

vite

I'm looking for a solution that lets me render markdown dynamically, based on the query string. At the moment I render markdown like this, in React + Vite:

import some other stuff...
import { useParams } from 'react-router-dom';
import { ReactComponent } from '../content/blog1.md';
const BlogPost = () => {
  const params = useParams();
  return (
    <Base>
      <PageTitle title={`title of blog ${params.blogId}`} />
      <ReactComponent />
    </Base>
  );
};
export default BlogPost;

What I would like is to pass the blogId to the import path like:

import { ReactComponent } from `../content/blog${params.blogId}.md`

Such that the correct file is imported on each /blog/* route. I tried this by lazy loading the markdown like:

const path = `../content/blog${params.blogId}.md`;
const Markdown = React.lazy(() => import(path));

But this raises errors and when I log Markdown I see

{$$typeof: Symbol(react.lazy), _payload: {…}, _init: ƒ}
$$typeof: Symbol(react.lazy)
_init: ƒ lazyInitializer(payload)
_payload: {_status: -1, _result: ƒ}

Which appears to be empty. What would be a solution to accomplish this?

like image 667
DSteman Avatar asked Jul 13 '26 02:07

DSteman


1 Answers

I had also issue when importing assets. In my case .md import failed.

import Article from './assets/article.md';

Failed to parse source for import analysis because the content contains invalid JS syntax. You may need to install appropriate plugins to handle the .md file format, or if it's an asset, add "**/*.md" to assetsInclude in your configuration

So I solved it adding assetsInclude: ['**/*.md'] setting to vite.config.js (for my .md files)

export default defineConfig({
  ...
  plugins: [react()],
  assetsInclude: ['**/*.md']
  ...
})

Eventually this started to work:

import("./assets/article.md").then(res => {
    fetch(res.default)
    .then(response => response.text())
    .then(text => console.log(text))
})

Docs are here:https://vitejs.dev/guide/assets.html Hope it helps.

Cheers.

like image 166
Witold Kaczurba Avatar answered Jul 15 '26 14:07

Witold Kaczurba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!