使用Vite2+Vue3渲染Markdown文档的方法实践

 更新时间:2021年08月03日 15:32:37   作者:木亦Sam  
本文主要介绍了Vite2+Vue3渲染Markdown文档的方法实践,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的可以了解一下

大部分使用 Vite2 的开发者遇到的一个问题,就是文档里并没有相关支持 Markdown 的介绍,那么如果想要在 Vite 项目中支持 Markdown 引入并渲染,需要怎么操作?这篇文章将介绍两种方式。

自定义 Vite 插件

如果去网上相关问题,大部分都是这种方式,就是自定义插件,使得 Vite 支持 Markdown 渲染,具体做法如下:

在项目根目录创建 md.js 文件,填充如下内容:

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: [ // 用于开发
      async ({ app }) => {
        app.use(async (ctx, next) => {
          // 获取后缀为 .md 的文件,将他变为 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 {
            await next();
          }
        });
      },
    ],
    transforms: [{  // 用于 rollup
      test: context => context.path.endsWith('.md'),
      transform: ({ code }) => mdToJs(code)
    }]
  };
}

接着修改 vite.config.js,引入上面创建的插件。

import {md} from './md';

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

这样,在使用时,会将导入的 md 文件转换成 js 文件渲染。具体使用示例:

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

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

  return {md}
  
  }
}

使用 vite-plugin-markdown

这款第三方插件不仅支持引入并渲染 Markdown 文件,并且支持渲染成各种格式,例入 HTML 字符串、React 或 Vue 的组件等。
安装 vite-plugin-markdown。

npm i vite-plugin-markdown

在 vite.config.js 中修改:

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

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

配置中传入一个 options,选项对象,支持以下参数:

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

markdown?: (body: string) => string

markdownIt?: MarkdownIt | MarkdownIt.Options

各个模式下的渲染示例:

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>

写在最后

到此这篇关于使用Vite2+Vue3渲染Markdown文档的方法实践的文章就介绍到这了,更多相关Vite2+Vue3渲染Markdown内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Vue 同步异步存值取值实现案例

    Vue 同步异步存值取值实现案例

    这篇文章主要介绍了Vue 同步异步存值取值实现案例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-08-08
  • Vue 图片压缩并上传至服务器功能

    Vue 图片压缩并上传至服务器功能

    这篇文章主要介绍了Vue 图片压缩并上传至服务器功能,本文通过实例代码给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-01-01
  • vue computed计算属性显示undefined的解决

    vue computed计算属性显示undefined的解决

    这篇文章主要介绍了vue computed计算属性显示undefined的解决方案,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-11-11
  • 使用vue-cli4.0快速搭建一个项目的方法步骤

    使用vue-cli4.0快速搭建一个项目的方法步骤

    这篇文章主要介绍了使用vue-cli4.0快速搭建一个项目的方法步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-12-12
  • 示例vue 的keep-alive缓存功能的实现

    示例vue 的keep-alive缓存功能的实现

    这篇文章主要介绍了示例vue 的keep-alive缓存功能的实现,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-12-12
  • vuex中store的action和mutations用法

    vuex中store的action和mutations用法

    这篇文章主要介绍了vuex中store的action和mutations用法,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-04-04
  • Vue 项目性能优化方案分享

    Vue 项目性能优化方案分享

    本文是作者通过实际项目的优化实践进行总结而来,希望读者读完本文,有一定的启发思考,从而对自己的项目进行优化起到帮助
    2022-08-08
  • 关于vue-i18n在单文件js中的使用

    关于vue-i18n在单文件js中的使用

    这篇文章主要介绍了关于vue-i18n在单文件js中的使用,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-09-09
  • 详解使用vue脚手架工具搭建vue-webpack项目

    详解使用vue脚手架工具搭建vue-webpack项目

    本篇文章主要介绍了详解使用vue脚手架工具搭建vue-webpack项目,非常具有实用价值,需要的朋友可以参考下
    2017-05-05
  • vuex分模块后,实现获取state的值

    vuex分模块后,实现获取state的值

    这篇文章主要介绍了vuex分模块后,实现获取state的值,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-07-07

最新评论