Nuxt UI componentDetection 漏检

解决 @nuxt/ui 开启 componentDetection 后,部分组件主题 CSS 未生成、样式完全缺失的问题。

问题现象

某 @nuxt/ui 组件 DOM 正常且无 JS 报错,但样式完全缺失(依赖 CSS 状态类的折叠、弹层定位等交互失效),开发与生产环境均能复现,关闭 componentDetection 后恢复。

常见于以下场景:

  • 使用 Nuxt Layer(extends),且组件在 modules/*/runtime/ 中引用
  • 使用 <component :is="dynamicComponent"> 动态渲染组件
  • 通过 provide/inject、插槽间接渲染,或在 server/ 中引用 UI 组件

定位方式

检查 .nuxt/ui.css 的 @source 列表是否包含对应组件的主题文件(以 Sidebar 为例):

grep "@source" .nuxt/ui.css
grep "sidebar" .nuxt/ui.css

若列表中缺少 ./ui/<component-name>.ts,即可确认属于静态扫描漏检,对应组件的 CSS 从未生成。

根本原因

componentDetection 默认只扫描各 Layer 的 app/ 目录以按需生成主题 CSS,不会扫描模块运行时目录及动态引用:

your-layer/
├── app/
│   ├── components/       ← 扫描(✅)
│   ├── pages/            ← 扫描(✅)
│   └── layouts/          ← 扫描(✅)
└── modules/
    └── your-module/
        └── runtime/      ← 不扫描(❌)

解决方案

将 componentDetection 从 true 改为显式数组,补充无法被静态扫描到的组件名(保留 app/ 的自动扫描):

nuxt.config.ts
export default defineNuxtConfig({
  ui: {
    experimental: {
      // 使用 PascalCase 且去掉 U 前缀,例如 <USidebar> -> 'Sidebar'
      componentDetection: [
        'Sidebar',
        'YourWidget'
      ]
    }
  }
})

修改后重启开发服务器,确认 .nuxt/ui.css 已生成对应条目:

grep "sidebar" .nuxt/ui.css
# 预期输出:@source "./ui/sidebar.ts";
若你是 Nuxt Layer 的维护者,建议直接在 Layer 的 nuxt.config.ts 中声明数组,避免接入方逐个修补。