文章目錄
- 前言
- 使用
- 基本使用
- 自定義渲染器
- 例子
- 代碼高亮
前言
最近嘗試了一下通過星火大模型將ai引入到項目上,但是ai返回的數據可以顯而易見的發現是markedown語法的,那么就需要一個工具,將類似這種的格式轉換為markdown格式
Marked 是一個用 JavaScript 編寫的開源庫,專注于把 Markdown 格式的文本解析并轉換為 HTML。它廣泛應用于各類 Web 應用程序、文檔生成工具、博客系統等場景中,實現 Markdown 到 HTML 的順暢轉換
然后我就搜索到了marked這個包,
使用
基本使用
官網
安裝
npm install marked
每個頁面引入如果是marked 那么所有頁面的設置將會通用
import { marked } from 'marked';
// or const { marked } = require('marked');const html = marked.parse('# Marked in Node.js\n\nRendered by **marked**.');
如果想要創建獨立的marked
import { Marked } from 'marked';
const marked = new Marked([options, extension, ...]);
使用
//markdownString:要解析的markdown,必須為字符串
//options:marked.js的配置
marked.parse(markdownString [,options])
options
自定義渲染器
自定義渲染器可以把解析后形成的數據再次進行二次修改
const renderer = new marked.Renderer();
渲染器方法:
例子
renderer.heading = (data) => {const { raw, text, depth } = data;console.log(text, depth);console.log()// 將一級標題轉換為h1標簽if (depth === 1) {return `<h1 class="hClass"> ${text}</h1>`;} else if (depth === 2) {return `<h2 class="hClass">${text}</h2>`;} else if (depth === 3) {return `<h3 class="hClass">${text}</h3>`;} else if (depth === 4) {return `<h4 class="hClass">${text}</h4>`;} else if (depth === 5) {return `<h5 class="hClass">${text}</h5>`;} else if (depth === 6) {return `<h6 class="hClass">${text}</h6>`;}
};
renderer.html = (html) => {console.log(html);const { text } = html;return `<div class="htmlClass">${text}</div>`;
};
marked.use(renderer);
當渲染到頁面上時
代碼高亮
在markedown中是不可避免有代碼塊的,但是markedown返回的數據并不會想當然的帶上樣式,我們需要自己進行設置
npm i highlight.js
npm i github-markdown-css
在main.js中寫一個全局自定義指令
import hljs from "highlight.js";
import "github-markdown-css";
import "highlight.js/styles/atom-one-dark.css";Vue.directive("highlight", function (el) {let blocks = el.querySelectorAll("pre code");blocks.forEach((block) => {hljs.highlightBlock(block);});
});
如果想要改變一些樣式的話 定義一個markdown樣式 這里我叫做 markedown-body
.markdown-body {font-family: Helvetica Neue, Helvetica, PingFang SC, Hiragino Sans GB,Microsoft YaHei, Arial, sans-serif !important;line-height: 20px;& ul {list-style: none;padding-left: 20px;}color: #000 !important;p {margin-top: 10px !important;margin-bottom: 10px !important;}pre {padding: 5px !important;margin-bottom: 10px !important;}.hljs {color: #abb2bf;background: #282c34;}.hClass {//出現#則不轉換為h1等標簽font-size: 16px;color: #8a2328;font-weight: 600;margin: 10px 0;}/* 只改變普通 code 標簽的顏色,不影響 pre 中的 code */code:not(pre) {color: red;font-weight: 600;background-color: rgba(175, 184, 193, 0.3);margin: 0 5px;}a {color: #1d71f7 !important;}
}