62 lines
2.0 KiB
TypeScript
62 lines
2.0 KiB
TypeScript
// 插件用于处理静态生成模式下的图片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}`
|
||
}
|
||
}
|
||
}
|
||
}) |