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

Vue implements student management function

This article example shares the specific code of ...

MySQL triggers: creating and using triggers

This article uses examples to describe the creati...

How to use MySQL stress testing tools

1. MySQL's own stress testing tool - Mysqlsla...

MySQL 5.7.20 Green Edition Installation Detailed Graphic Tutorial

First, let’s understand what MySQL is? MySQL is a...

Detailed explanation of JavaScript timers

Table of contents Brief Introduction setInterval ...

How to configure VMware multi-node environment

This tutorial uses CentOS 7 64-bit. Allocate 2GB ...

How to write a MySQL backup script

Preface: The importance of database backup is sel...

How to use Vue+ElementUI Tree

The use of Vue+ElementUI Tree is for your referen...

MySQL database terminal - common operation command codes

Table of contents 1. Add users 2. Change the user...

2 methods and precautions for adding scripts in HTML

How to add <script> script in HTML: 1. You c...

How to Install Oracle Java 14 on Ubuntu Linux

Recently, Oracle announced the public availabilit...

Node.js makes a simple crawler case tutorial

Preparation First, you need to download nodejs, w...

Browser compatibility summary of common CSS properties (recommended)

Why do we need to summarize the browser compatibi...

What to do if you forget the initial password when installing MySQL on Mac

Forgetting the password is a headache. What shoul...