思路整理:将md文件转化成html--个人遇到的坑点与个人知识总结

时间:2025-04-08 14:08:24

环境:vue3  vite版本:  开发语言: ts          =》vue3+vite2+ts

感觉1:版本过低遇到的问题------》总结在使用一些插件时需要注意改插件使用的环境是否符合当前版本

感觉2:文档理解----》更多的时候推荐全看官网

使用插件: vite-plugin-markdown  

实现将md转为html的方法很多,为什么选择vite-plugin-markdown ,理由如下:-plugin-markdown 可以支持多种语言的转换,2.没有要求高版本vite。

具体实现步骤:官网

步骤1:插入vite-plugin-markdown插件 :  

yarn add vite-plugin-markdown -D

or

npm i -D vite-plugin-markdown

步骤2: 添加配置  在中添加如下配置 【重点:这一步的目的是为了添加这个插件的相应的配置,方便后面项目的使用】

官网写法

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

 = {
  plugins: [mdPlugin(options)]
}

个人写法:

// 在新的ts文件中写入一个方法
import mdPlugin, { Mode } from 'vite-plugin-markdown'

export default function setPlugins() {
  const plugins: Plugin[] = [
    ...
    mdPlugin({
      mode: []
    }),
}


// 在config中调用方法

// plugins属性
plugins: setPlugins()

步骤3:导入md文件

import { html } from './'


// 使用
<div v-html = "html"></div>

步骤4:实现代码高亮

导入插件highlight

npm install  -D

or

yarn add  -D

步骤5: 自定义v-highlight指令   

import hljs from ''; // 高亮
import '/styles/' 

// vue3
('highlight',function (el) {
  let blocks = ('pre code');
  ((block: HTMLElement)=>{
    (block)
  })
})

步骤6: 使用自定义指令

<div v-highlight v-html= "html"></div>

最后一步:在ts中需要声明你需要的.md文件

declare module '*.md' {
  // "unknown" would be more detailed depends on how you structure frontmatter
  const attributes: Record<string, unknown>; 

  // When "" is requested
  const toc: { level: string, content: string }[];

  // When "" is requested
  const html: string;

  // When "" is requested. VFC could take a generic like <{ MyComponent: TypeOfMyComponent }>
  import React from 'react'
  const ReactComponent: ;
  
  // When "" is requested
  import { ComponentOptions, Component } from 'vue';
  const VueComponent: ComponentOptions;
  const VueComponentWith: (components: Record<string, Component>) => ComponentOptions;

  // Modify below per your usage
  export { attributes, toc, html, ReactComponent, VueComponent, VueComponentWith };
}

实现md文本中的文字的样式

理解:我们将md文件转为html文件,那么在浏览器显示的就是html文件,这样的话,我们修改样式可以直接像普通的html一样写,需要注意的是我们修改另一个文件中的样式,需要进行穿(:deep)

举个例子:

<div v-highlight v-html= "html" class="heightLight"></div>

// 样式  css
.heightLight :deep(p){
    color:red;
}


// 样式 less  vue3
.heightLight {
    :deep(p){
        color:red;
    }
}