Practice of using Vite2+Vue3 to render Markdown documents

Practice of using Vite2+Vue3 to render Markdown documents

A problem encountered by most developers using Vite2 is that there is no introduction to supporting Markdown in the documentation. So what should you do if you want to support Markdown import and rendering in the Vite project? This article will introduce two methods.

Custom Vite plugins

If you look at related questions online, most of them are in this way, that is, custom plug-ins to make Vite support Markdown rendering. The specific steps are as follows:

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

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 async ({ app }) => {
        app.use(async (ctx, next) => {
          // Get the file with the suffix .md and turn it into a js file if (ctx.path.endsWith('.md')) {             
            ctx.type = 'js';
            const filePath = path.join(process.cwd(), ctx.path);
            ctx.body = mdToJs(fs.readFileSync(filePath).toString());
          } else {
            await next();
          }
        });
      },
    ],
    transforms: [{ // for rollup
      test: context => context.path.endsWith('.md'),
      transform: ({ code }) => mdToJs(code)
    }]
  };
}

Then modify vite.config.js and import the plugin created above.

import {md} from './md';

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

In this way, when used, the imported md file will be converted into a js file for rendering. Specific usage examples:

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

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

  return {md}
  
  }
}

Using vite-plugin-markdown

This third-party plugin not only supports the import and rendering of 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

Modify in vite.config.js:

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

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

An options object is passed into the configuration, which supports the following parameters:

mode?: ('html' | 'toc' | 'react' | 'vue')[]

markdown?: (body: string) => string

markdownIt?: MarkdownIt | MarkdownIt.Options

Rendering examples in each mode:

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'] }

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>"

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' },]

Import as a React component (Mode.REACT)

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

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

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>

Final Thoughts

This is the end of this article about the practice of using Vite2+Vue3 to render Markdown documents. For more relevant Vite2+Vue3 rendering Markdown content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Vue3 navigation bar component encapsulation implementation method
  • Vue3 Vue Event Handling Guide
  • In-depth explanation of the style feature in Vue3 single-file components
  • vue3.0+echarts realizes three-dimensional column chart
  • This article will show you how to use Vue 3.0 responsive
  • Detailed explanation of the underlying principle of defineCustomElement added in vue3.2
  • Vue3 + TypeScript Development Summary
  • Vue3+TypeScript implements a complete example of a recursive menu component
  • Vue3 implements a todo-list
  • Vue3+script setup+ts+Vite+Volar project
  • How to implement logic reuse with Vue3 composition API
  • Vue3 realizes the image magnifying glass effect
  • Implementation of vue3.0+vant3.0 rapid project construction
  • Vue3 Documentation Quick Start

<<:  Use of Linux cal command

>>:  MySQL index usage monitoring skills (worth collecting!)

Recommend

XHTML tags that are easily confused by the location of the use

<br />We have always emphasized semantics in...

Public free STUN servers

Public free STUN servers When the SIP terminal us...

JavaScript imitates Jingdong magnifying glass effect

This article shares the specific code for JavaScr...

A brief analysis of the count tracking of a request in nginx

First, let me explain the application method. The...

JavaScript event capture bubbling and capture details

Table of contents 1. Event Flow 1. Concept 2. DOM...

Using Vue to implement timer function

This article example shares the specific code of ...

uniapp dynamic modification of element node style detailed explanation

Table of contents 1. Modify by binding the style ...

Mysql Sql statement exercises (50 questions)

Table name and fields –1. Student List Student (s...

Summary of common MySQL table design errors

Table of contents Mistake 1: Too many columns of ...

Solution to MySQL remote connection failure

I have encountered the problem that MySQL can con...

How to create, save, and load Docker images

There are three ways to create an image: creating...

wget downloads the entire website (whole subdirectory) or a specific directory

Use wget command to download the entire subdirect...

Complete steps to install boost library under linux

Preface The Boost library is a portable, source-c...

Implementation of MySQL custom list sorting by specified field

Problem Description As we all know, the SQL to so...