tuanshiwei-web/plugins/cdn-image.ts
2025-05-24 09:12:30 +08:00

62 lines
2.0 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 插件用于处理静态生成模式下的图片CDN路径
import { defineNuxtPlugin } from '#app'
export default defineNuxtPlugin(() => {
// CDN基础URL
const cdnBaseUrl = 'https://cdn.web.0rui.cn/'
// 创建一个全局方法用于转换图片路径
return {
provide: {
// 转换图片路径为CDN路径
cdnImage: (path: string) => {
// 如果路径已经是完整的URL则直接返回
if (path.startsWith('http://') || path.startsWith('https://')) {
return path
}
// 判断是否为图片资源
const isImage = /\.(jpg|jpeg|png|gif|svg|webp)$/i.test(path)
if (!isImage) {
return path // 非图片资源直接返回原路径
}
// 处理以public开头的路径
if (path.startsWith('public/')) {
return `${cdnBaseUrl}${path.replace('public/', '')}`
}
// 处理以/public开头的路径
if (path.startsWith('/public/')) {
return `${cdnBaseUrl}${path.replace('/public/', '')}`
}
// 处理以img/开头的路径
if (path.startsWith('img/')) {
return `${cdnBaseUrl}${path}`
}
// 处理以/img开头的路径
if (path.startsWith('/img/')) {
return `${cdnBaseUrl}${path.substring(1)}`
}
// 处理以_nuxt开头的路径
if (path.startsWith('/_nuxt/')) {
// 提取_nuxt后面的路径部分
const pathWithoutPrefix = path.replace('/_nuxt/', '')
// 如果路径包含img/,保留该结构
if (pathWithoutPrefix.includes('img/')) {
return `${cdnBaseUrl}${pathWithoutPrefix}`
} else {
// 否则添加img/前缀
return `${cdnBaseUrl}img/${pathWithoutPrefix}`
}
}
// 其他情况直接拼接CDN基础URL和路径
return `${cdnBaseUrl}img/${path}`
}
}
}
})