markdown-it
Markdown-it是一个功能强大的Markdown解析库,适用于JavaScript环境。以下是对Markdown-it的详细介绍:
一、简介
Markdown-it支持丰富的Markdown语法,并能够将Markdown文本轻松转换为HTML格式。它拥有丰富的插件和配置选项,使得文档编辑更加灵活多变。此外,Markdown-it还提供了高性能和高度可配置性,确保跨平台一致性。
二、安装与使用
1、安装:在命令行中输入
npm install markdown-it
或
yarn add markdown-it
2、使用:可以通过以下方式使用Markdown-it。
const markdownIt = require('markdown-it')();
const md = markdownIt.render('# Hello, markdown-it!');
console.log(md);
// 运行上述代码后,会在控制台看到HTML输出:“**Hello, markdown-it!**”。
VUE中使用方式
import Markdown from "markdown-it";
data() {
return {
md: new Markdown(),
};
},
this.md.render(this.answer)
例:
配合使用typed.js,实现打字机效果,进而实现一问一答的形式
<template>
<div v-if="answer" class="reply" ref="list">
<div v-for="(item, index) in historyList" :key="item?.id || index">
<!-- 问题 -->
<div class="qustion">{{ item.q }}</div>
<!-- AI回复内容 -->
<div
v-if="item.typedId"
:id="item.typedId"
ref="answerArea"
class="replyText"
></div>
</div>
</div>
</template>
<script>
import Markdown from "markdown-it";
import Typed from "typed.js";
export default {
data() {
return {
md: new Markdown(),
answer: "",
historyList: [],
};
},
methods: {
getExtChat() {
if (this.historyList.length <= 0) {
this.historyList.push({ q: this.textareaValue });
}
let params = {
userId: "用户id",
question: "这是一个问题?",
streaming: true,
networking: false,
networkType: "",
customPrompt: "",
model: "",
};
extChat(params)
.then((res) => {
if (res.code === 200) {
this.answer = res.response;
this.historyList.push({
q: res.question,
a: res.response,
typedId: "id" + res.qa_id,
})
this.initType("id" + res.qa_id);
} else {
this.$message.error(res.msg);
}
})
.catch((err) => {
this.$message.error(err);
})
.finally(() => {
});
},
// 配置Typed
initType(typedId) {
this.$nextTick(() => {
const options = {
strings: [this.md.render(this.answer)],
typeSpeed: 0.25, // 打印速度
backSpeed: 0, //删除速度,为0不删除
startDelay: 10, // 开始之前的延迟300毫秒
loop: false, // 是否循环
showCursor: false,
autoInsertCss: false, //是否自动插入CSS样式表,设置为false以避免与Vue的样式冲突
onComplete: () => {
//打印机效果完成时的钩子函数(onComplete--文本已完全显示)
clearInterval(this.timer); //这个定时器我是不停调用,停止文本超出实时top滚动
},
};
this.typedInstance = new Typed(`#${typedId}`, options);
this.scrollTop(); //调用了定时器,实时更新dom的scrollTop
});
},
}
}
</script>
三、链接
Markdown官方教程
markdow-it 中文文档
typed.js
四、Q&A
本机node、npm与yarn版本

依赖版本
"markdown-it": "^14.1.0",
"typed.js": "^2.1.0",
使用yarn add markdown-it 安装后,项目无法启动,报错信息如下:

修改vue.config.js 配置
module.export = {
chainWebpack(config){
config.module
.rule('mjs')
.test(/\.mjs$/)
.include
.add(path.resolve(__dirname, 'node_modules')) // 确保包含 node_modules
.end()
.type('javascript/auto'); // 允许 Webpack 根据文件内容自动决定是使用 ES 模块还是 CommonJS 模块
}
}
其他node版本不知是否存在该问题,大家可以尝试看
Markdown-it解析库介绍与使用
6524

被折叠的 条评论
为什么被折叠?



