环境:vue3 vite版本:2.x.x 开发语言: ts =》vue3+vite2+ts
感觉1:版本过低遇到的问题------》总结在使用一些插件时需要注意改插件使用的环境是否符合当前版本
感觉2:文档理解----》更多的时候推荐全看官网
使用插件: vite-plugin-markdown highlight.js
实现将md转为html的方法很多,为什么选择vite-plugin-markdown ,理由如下:1.vite-plugin-markdown 可以支持多种语言的转换,2.没有要求高版本vite。
具体实现步骤:官网
步骤1:插入vite-plugin-markdown插件 :
yarn add vite-plugin-markdown -D
or
npm i -D vite-plugin-markdown
步骤2: 添加配置 在vite.config.ts中添加如下配置 【重点:这一步的目的是为了添加这个插件的相应的配置,方便后面项目的使用】
官网写法
const mdPlugin = require('vite-plugin-markdown')
module.exports = {
plugins: [mdPlugin(options)]
}
个人写法:
// 在新的ts文件中写入一个方法
import mdPlugin, { Mode } from 'vite-plugin-markdown'
export default function setPlugins() {
const plugins: Plugin[] = [
...
mdPlugin({
mode: [Mode.HTML]
}),
}
// 在config中调用方法
// plugins属性
plugins: setPlugins()
步骤3:导入md文件
import { html } from './Use.md'
// 使用
<div v-html = "html"></div>
步骤4:实现代码高亮
导入插件highlight
npm install highlight.js -D
or
yarn add highlight.js -D
步骤5: 自定义v-highlight指令
main.ts
import hljs from 'highlight.js'; // 高亮
import 'highlight.js/styles/atom-one-dark.css'
// vue3
app.directive('highlight',function (el) {
let blocks = el.querySelectorAll('pre code');
blocks.forEach((block: HTMLElement)=>{
hljs.highlightBlock(block)
})
})
步骤6: 使用自定义指令
<div v-highlight v-html= "html"></div>
最后一步:在ts中需要声明你需要的.md文件
xx.d.ts
declare module '*.md' {
// "unknown" would be more detailed depends on how you structure frontmatter
const attributes: Record<string, unknown>;
// When "Mode.TOC" is requested
const toc: { level: string, content: string }[];
// When "Mode.HTML" is requested
const html: string;
// When "Mode.React" is requested. VFC could take a generic like React.VFC<{ MyComponent: TypeOfMyComponent }>
import React from 'react'
const ReactComponent: React.VFC;
// When "Mode.Vue" 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;
}
}