One of the problems most Vite2 developers encounter is that there is no documentation to support Markdown. What do you need to do to support Markdown introduction and rendering in a Vite project? This article will introduce two approaches.

Custom Vite plug-in

If you go to the Internet related questions, most of the way is this way, is a custom plug-in, make Vite support Markdown rendering, the specific approach is as follows:

Create an md.js file in the project root directory and fill it with the following contents:

import path from 'path';
import fs from 'fs';
import marked from 'marked';

const mdToJs = str= > {
  const content = JSON.stringify(marked(str));
  return `export default ${content}`;
};


export function md() {
  return {
    configureServer: [ // For development purposes
      async ({ app }) => {
        app.use(async (ctx, next) => {
          // get the.md file and change it to js
          if (ctx.path.endsWith('.md')) {             
            ctx.type = 'js';
            const filePath = path.join(process.cwd(), ctx.path);
            ctx.body = mdToJs(fs.readFileSync(filePath).toString());
          } else {
            awaitnext(); }}); },].transforms: [{  / / for a rollup
      test: context= > context.path.endsWith('.md'),
      transform: ({ code }) = > mdToJs(code)
    }]
  };
}
Copy the code

Then modify vite.config.js to introduce the plug-in created above.

import {md} from './md';

export default {
  plugins: [md()]
};
Copy the code

This will convert the imported MD file to a JS file for rendering when used. Specific usage examples:

<template>
<article v-html="md" />
</template>

<script lang="ts">
import md from './xxx.md'
export default {
setup(){

  return {md}
  
  }
}
Copy the code

Use the vite – plugin – markdown

This third party plugin not only supports importing and rendering Markdown files, but also supports rendering into various formats, such as HTML strings, React or Vue components, etc.

Install vite – plugin – markdown.

npm i vite-plugin-markdown
Copy the code

Modify in vite.config.js:

const mdPlugin = require('vite-plugin-markdown')

export default {
  plugins: [
    mdPlugin.plugin({
      mode: ['html'],})]}Copy the code

The configuration passes in an options object that supports the following parameters:

mode? : ('html' | 'toc' | 'react' | 'vue')[] markdown? :(body: string) = >string markdownIt? : MarkdownIt | MarkdownIt.OptionsCopy the code

Examples of rendering in various modes:

Import Front Matter attributes

---
title: Awesome Title
description: Describe this awesome content
tags:
  - "great"
  - "awesome"
  - "rad"
---
# This is awesome
Vite is an opinionated web dev build tool that serves your code via native ES Module imports during dev and bundles it with Rollup for production.

import { attributes } from './contents/the-doc.md';

console.log(attributes) //=> { title: 'Awesome Title', description: 'Describe this awesome content', tags: ['great', 'awesome', 'rad'] }
Copy the code

Import compiled HTML (Mode.HTML)

import { html } from './contents/the-doc.md';

console.log(html) 
//=> "<h1>This is awesome</h1><p>ite is an opinionated web dev build tool that serves your code via native ES Module imports during dev and bundles it with Rollup for production.</p>"
Copy the code

Import ToC metadata (Mode.TOC)

# vite

Vite is an opinionated web dev build tool that serves your code via native ES Module imports during dev and bundles it with Rollup for production.

## Status

## Getting Started

# Notes

import { toc } from './contents/the-doc.md'

console.log(toc)
//=> [{ level: '1', content: 'vite' }, { level: '2', content: 'Status' }, { level: '2', content: 'Getting Started' }, { level: '1', content: 'Notes' },]
Copy the code

Import as a React component (Mode.REACT)

import React from 'react'
import { ReactComponent } from './contents/the-doc.md'

function MyReactApp() {
  return (
    <div>
      <ReactComponent />
    </div>
}
Copy the code

Import as a Vue component (Mode.VUE)

<template>
  <article>
    <markdown-content />
  </article>
</template>

<script>
import { VueComponent } from './contents/the-doc.md'

export default {
  components: {
    MarkdownContent: VueComponent
  }
};
</script>
Copy the code

Write in the last

Writing is not easy, I hope I can get a “like” from you. If the article is useful to you, choose “bookmark”. If there are any mistakes or suggestions, please comment and correct them. Thank you. ❤ ️

Welcome to other articles

  • Internationalize your website with Vite2+Vue3 | August Update Challenge
  • Actual combat: The front-end interface request parameters are confused
  • Practice: Implement a Message component with Vue3
  • Actual combat: Vue3 Image components, incidentally support lazy loading
  • What updates does One Piece, vue.js 3.0 bring
  • An article digests the major new features of ES7, ES8, and ES9
  • Common problems and solutions for technical teams
  • Introduction to 10 common new features in ES6
  • Vue3 script Setup syntax is really cool