目录
  • 自定义 vite 插件
    • 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) 
    //=> "<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内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!