vuepress 主题组件覆写与路径导入问题
约 546 字大约 2 分钟
vuepress-theme-plume
是一个很美观的 VuePress 主题呢,使用的人也很多 但嘛,人总想有点个性,总想改点样式,于是就开始了这次小折腾
以前的做法:直接复制主题
之前我修改样式是直接把原有主题整个丢进 /docs/.vuepress/theme
里改。 这样虽然能改,但主题更新就麻烦了,改一次就要对比一次,好麻烦
现在要用官方推荐的覆写方式
这次我决定用 官方推荐的覆写组件方式
但要覆写时遇到了路径导入问题,来记录一下解决过程
遇到的问题:相对路径失效
原本主题里是这样导入的:
import { useData, useInternalLink, useTagColors } from '../../composables/index.js'
但覆写时文件路径不一样,这种相对路径就会失效,报错
我就想:
那要怎么从覆写组件里导入主题内的可组合函数呢?
尝试使用 @theme
别名
我看到文档里提到 @theme
,试着写成:
import { useData } from '@theme/../composables/index.js'
结果报错了
再去翻文档:
主题会给非全局组件加上
@theme
别名前缀,例如@theme/VPFooter.vue
。
说明:
@theme
是主题组件目录的别名。- 不能用
../
从@theme
向上跳,会解析出错
又去翻主题源码:
function setupAlias() {
return {
...Object.fromEntries(
fs.readdirSync(resolve("client/components"), { recursive: true })
.filter(file => file.endsWith(".vue"))
.map(file => [path.join("@theme", file), resolve("client/components", file)])
)
}
}
确认了 @theme
只 alias 了 /components
下的 .vue
文件。
正确做法:使用包内 exports
问了 Claude,Claude说可以看主题的 package.json
的 exports
字段
果然找到了:
"exports": {
".": { "types": "./lib/node/index.d.ts", "import": "./lib/node/index.js" },
"./client": { "types": "./lib/client/index.d.ts", "import": "./lib/client/index.js" },
"./components/*": { "import": "./lib/client/components/*" },
"./composables": { "types": "./lib/client/composables/index.d.ts", "import": "./lib/client/composables/index.js" },
...
}
说明: ✅ 如果要使用主题提供的 composables,应直接写成:
import { useData, useInternalLink, useTagColors } from 'vuepress-theme-plume/composables'
而不是去写绝对路径或者 @theme
+ 跳目录的方式
总结
- 不要再复制整个主题文件夹来改样式。
- 覆写组件时,如需导入主题内部提供的 composables,直接使用包名 + 导出路径(遵循
exports
)。 - 使用官方推荐的覆写方式更优雅,也方便后续更新主题