Skip to content

Instantly share code, notes, and snippets.

@AmanuelCh
Created August 19, 2024 22:06
Show Gist options
  • Save AmanuelCh/d38c39192986eea7daf674b65ceecca7 to your computer and use it in GitHub Desktop.
Save AmanuelCh/d38c39192986eea7daf674b65ceecca7 to your computer and use it in GitHub Desktop.
Import markdown files in .tsx file for a vite project

first in your vite-env.d.ts file, put the following line to let typescript treat .md files as a module.

declare module '*.md';

then in your vite.config.ts file put the following code to create a custom plugin which loads .md files and gets the raw content of the .md file

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    react(),
    // Custom plugin to load markdown files
    {
      name: 'markdown-loader',
      transform(code, id) {
        if (id.slice(-3) === '.md') {
          // For .md files, get the raw content
          return `export default ${JSON.stringify(code)};`;
        }
      },
    },
  ],
});

Demo

import markdown from './my-markdown.md';

const DemoComponent = () => {
  return (
    <div>{markdown}</div>
  )
}

you can use packages like react-markdown to nicely display the markdown file.

and there you go, you can now import markdown file in your project 🙂

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment