Skip to content

Commit d15e50c

Browse files
committed
fix: 首页图片Hash
1 parent ec38902 commit d15e50c

File tree

1 file changed

+18
-1
lines changed

1 file changed

+18
-1
lines changed

.vitepress/theme/composables/posts.data.ts

+18-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
import { createContentLoader } from 'vitepress'
22
import { EXCERPT_LENGTH, EXCERPT_MARK, POST_FILES } from '../../constants'
3+
import { fileURLToPath } from 'url'
4+
import { createHash } from 'crypto'
5+
import { readFileSync } from 'fs'
6+
import { parse } from 'path'
37

48
export interface Post {
59
title: string
@@ -51,14 +55,27 @@ export default createContentLoader(POST_FILES, {
5155
*/
5256
function updateImageSrc(excerpt: string | undefined, urlPrefix: string) {
5357
if (excerpt == undefined) return
58+
5459
return excerpt.replace(
5560
/<img\s+([^>]*?)src=["']\.\/([^"']*?)["']([^>]*?)>/gi,
5661
(match, p1, p2, p3) => {
57-
return `<img ${p1}src="${urlPrefix}${p2}"${p3}>`
62+
const imageUrl = fileToUrl(urlPrefix + p2)
63+
return `<img ${p1}src="${imageUrl}"${p3}>`
5864
}
5965
)
6066
}
6167

68+
function fileToUrl(file: string) {
69+
if (process.env.NODE_ENV !== 'production') return file
70+
const path = fileURLToPath(new URL('../../../' + file, import.meta.url))
71+
const parsed = parse(path)
72+
const hash = createHash('sha256')
73+
.update(readFileSync(path))
74+
.digest('hex')
75+
.slice(0, 8)
76+
return `/assets/${parsed.name}.${hash}${parsed.ext}`
77+
}
78+
6279
function generateTitle(
6380
frontmatter: Record<string, any>,
6481
src: string | undefined

0 commit comments

Comments
 (0)