From 9a64ee07bfa8b54b585a05c39d03c24e9cff507d Mon Sep 17 00:00:00 2001 From: pengzhanbo Date: Wed, 10 Jul 2024 07:37:12 +0800 Subject: [PATCH] =?UTF-8?q?perf(plugin-md-power):=20=E4=BC=98=E5=8C=96=20i?= =?UTF-8?q?cons=20css=20=E8=BE=93=E5=87=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/node/features/icons/writer.ts | 30 ++++++++++++++++--- 1 file changed, 26 insertions(+), 4 deletions(-) diff --git a/plugins/plugin-md-power/src/node/features/icons/writer.ts b/plugins/plugin-md-power/src/node/features/icons/writer.ts index b6f156eb..f279b13b 100644 --- a/plugins/plugin-md-power/src/node/features/icons/writer.ts +++ b/plugins/plugin-md-power/src/node/features/icons/writer.ts @@ -1,3 +1,4 @@ +import { constants, promises as fsp } from 'node:fs' import type { App } from 'vuepress/core' import { getIconContentCSS, getIconData } from '@iconify/utils' import { fs, logger } from 'vuepress/utils' @@ -15,6 +16,7 @@ export interface IconCacheItem { const nanoid = customAlphabet('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', 8) const iconDataCache = new Map() const URL_CONTENT_RE = /(url\([^]+?\))/ +const CSS_PATH = 'internal/md-power/icons.css' function resolveOption(opt?: boolean | IconsOptions): Required { const options = typeof opt === 'object' ? opt : {} @@ -27,8 +29,16 @@ function resolveOption(opt?: boolean | IconsOptions): Required { export function createIconCSSWriter(app: App, opt?: boolean | IconsOptions) { const cache = new Map() const isInstalled = isPackageExists('@iconify/json') + const currentPath = app.dir.temp(CSS_PATH) - const write = (content: string) => app.writeTemp('internal/md-power/icons.css', content) + const write = async (content: string) => { + if (!content && app.env.isDev) { + if (existsSync(currentPath) && (await fsp.stat(currentPath)).isFile()) { + return + } + } + await app.writeTemp(CSS_PATH, content) + } let timer: NodeJS.Timeout | null = null const options = resolveOption(opt) @@ -42,10 +52,12 @@ export function createIconCSSWriter(app: App, opt?: boolean | IconsOptions) { timer = setTimeout(async () => { let css = defaultContent - for (const [, { content, className }] of cache) - css += `.${className} {\n --svg: ${content};\n}\n` + if (cache.size > 0) { + for (const [, { content, className }] of cache) + css += `.${className} {\n --svg: ${content};\n}\n` - await write(css) + await write(css) + } }, 100) } @@ -132,3 +144,13 @@ async function genIconContent(iconName: string, cb: (content: string) => void) { const match = content.match(URL_CONTENT_RE) return cb(match ? match[1] : '') } + +function existsSync(fp: string) { + try { + fs.accessSync(fp, constants.R_OK) + return true + } + catch { + return false + } +}