温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何使用Vite2+Vue3渲染Markdown文档

发布时间:2021-08-03 17:18:19 来源:亿速云 阅读:351 作者:chen 栏目:开发技术

本篇内容主要讲解“如何使用Vite2+Vue3渲染Markdown文档”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“如何使用Vite2+Vue3渲染Markdown文档”吧!

目录
  • 自定义 Vite 插件

  • 使用 vite-plugin-markdown

    • Import Front Matter attributes

    • Import compiled HTML (Mode.HTML)

    • Import ToC metadata (Mode.TOC)

    • Import as a React component (Mode.REACT)

    • Import as a Vue component (Mode.VUE)


大部分使用 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) 
//=> "<h2>This is awesome</h2><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文档”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI