From 3353c58900535efa69d34e7c7c7479fcc9496f3f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=97=B6=E7=91=BE?= Date: Tue, 6 Aug 2024 02:41:43 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E4=BF=AE=E6=AD=A3=E7=9B=B8=E5=AF=B9?= =?UTF-8?q?=E8=B7=AF=E5=BE=84=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/index.ts | 31 +++++++++++++++++++++++++++---- 1 file changed, 27 insertions(+), 4 deletions(-) diff --git a/src/index.ts b/src/index.ts index 29023dc..0b73331 100644 --- a/src/index.ts +++ b/src/index.ts @@ -7,6 +7,8 @@ import { fileURLToPath } from 'url' import markedAlert from 'marked-alert' import markedKatex from 'marked-katex-extension' import { GithubMarkdownThemes, HighlightJsThemes } from './styles' +import { createRequire } from 'module' +const require = createRequire(import.meta.url) /** 提取 KatexOptions 类型 */ export type KatexOptions = Parameters[0] @@ -40,16 +42,37 @@ export default class Markdown { highlight: string /** marked 实例 */ marked: typeof marked + /** github-markdown-css npm包路径 */ + npm_github_markdown_css: string + /** highlight.js npm包路径 */ + npm_highlight_js: string constructor (config: Options) { this.config = config this.templatepath = pkgpath + '/index.html' this.template = '' - this.gitcss = `./node_modules/github-markdown-css/${GithubMarkdownThemes.GitHub}` - this.highlight = `./node_modules/highlight.js/styles/${HighlightJsThemes.GitHub}` + this.npm_github_markdown_css = this.findPackageRoot(require.resolve('github-markdown-css')) + this.npm_highlight_js = this.findPackageRoot(require.resolve('highlight.js')) + + this.gitcss = `${this.npm_github_markdown_css}/${GithubMarkdownThemes.GitHub}` + this.highlight = `${this.npm_highlight_js}/styles/${HighlightJsThemes.GitHub}` this.marked = marked this.init() } + /** + * 查找包根目录 + * @param dir - 当前目录 + * @returns - 包根目录 + */ + findPackageRoot (dir: string): string { + if (fs.existsSync(path.join(dir, 'package.json'))) return dir + const parentDir = path.dirname(dir) + if (parentDir === dir) { + throw new Error('Cannot find package root directory') + } + return this.findPackageRoot(parentDir) + } + init () { /** 使用自定义渲染器来进行代码高亮并添加行号 */ const renderer: any = { @@ -73,8 +96,8 @@ export default class Markdown { this.marked.use(markedKatex(this.config?.katex)) /** 检查是否有传入样式 */ - if (this.config?.gitcss) this.gitcss = `./node_modules/github-markdown-css/${this.config.gitcss}` - if (this.config?.highlight) this.highlight = `./node_modules/highlight.js/styles/${this.config.highlight}` + if (this.config?.gitcss) this.gitcss = `${this.npm_github_markdown_css}/${this.config.gitcss}` + if (this.config?.highlight) this.highlight = `${this.npm_highlight_js}/styles/${this.config.highlight}` /** 检查是否有传入模板 */ if (this.config?.template) {