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

PNG Alpha Transparency in IE6 (Complete Collection)

Many people say that IE6 does not support PNG tra...

Detailed tutorial on installing MySQL database on Alibaba Cloud Server

Table of contents Preface 1. Uninstall MySQL 2. I...

Nodejs-cluster module knowledge points summary and example usage

The interviewer will sometimes ask you, tell me h...

MySQL Full-text Indexing Guide

Full-text indexing requires special query syntax....

Detailed steps for building Portainer visual interface with Docker

In order to solve the problem mentioned last time...

Docker Compose installation and usage steps

Table of contents 1. What is Docker Compose? 2. D...

MySQL replication advantages and principles explained in detail

Replication is to transfer the DDL and DML operat...

N ways to align the last row of lists in CSS flex layout to the left (summary)

I would like to quote an article by Zhang Xinxu a...

Detailed explanation of Excel parsing and exporting based on Vue

Table of contents Preface Basic Introduction Code...

Combining XML and CSS styles

student.xml <?xml version="1.0" enco...

How to use JavaScript to determine several common browsers through userAgent

Preface Usually when making h5 pages, you need to...

Two simple menu navigation bar examples

Menu bar example 1: Copy code The code is as foll...