You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NuxtApp中$pb类型显示Unknown而非PocketBase的解决办法

解决Nuxt中useNuxtApp().$pb类型为Unknown的问题

问题描述

按照Nuxt官方插件类型定义文档说明,向useNuxtApp添加provider时应自动生成对应类型,但实际开发中,调用useNuxtApp().$pb时类型显示为Unknown,而非预期的PocketBase类型。尽管在plugins/pocketbase.ts中provider返回的pb是正确的PocketBase类型,但类型推导未生效。

相关代码:

// composables/useUserStore.ts
export const useUserStore = ()=>{
  const loginWithEmailAndPassword = async (email:string,password:string)=>{
    return await useNuxtApp().$pb.collection('users').authWithPassword(email,password)
  }
}
// plugins/pocketbase.ts
import PocketBase from 'pocketbase';

export default defineNuxtPlugin(async () => {
  const pb = new PocketBase('http://127.0.0.1:8090');

  const cookie = useCookie<{token:string,model:any}>("pb_auth", {
    path:     "/",
    secure:   true,
    sameSite: "strict",
    httpOnly: false, // change to "true" if you want only server-side access
    maxAge:   604800,
  })

  // load the store data from the cookie value
  pb.authStore.save(cookie.value?.token, cookie.value?.model);

  // send back the default 'pb_auth' cookie to the client with the latest store state
  pb.authStore.onChange(() => {
    console.log(pb.authStore.model)
    cookie.value = {
      token: pb.authStore.token,
      model: pb.authStore.model,
    };
  },true);

  try {
      // get an up-to-date auth store state by verifying and refreshing the loaded auth model (if any)
      pb.authStore.isValid && await pb.collection('users').authRefresh();
  } catch (_) {
      // clear the auth store on failed refresh
      pb.authStore.clear();
  }

  return {
    provide: { pb }
  }
});

解决方案

由于异步插件的类型自动推导存在局限性,需手动扩展Nuxt类型定义解决该问题:

  1. 创建类型声明文件
    在项目根目录新建types/nuxt.d.ts文件(无types文件夹则先创建),添加以下内容:
import type PocketBase from 'pocketbase';

declare module '#app' {
  interface NuxtApp {
    $pb: PocketBase;
  }
}

// 兼容老版本Nuxt类型(Nuxt 3可忽略)
declare module '@nuxt/types' {
  interface NuxtAppOptions {
    $pb: PocketBase;
  }
}

export {};
  1. 配置tsconfig.json
    确保tsconfig.json的include字段包含类型目录,让TypeScript识别新类型定义:
{
  "include": [
    "types/**/*",
    ".nuxt/**/*",
    "plugins/**/*",
    "composables/**/*"
  ]
}
  1. 重启开发服务
    关闭当前Nuxt开发服务后重新启动,TypeScript会加载新类型定义,此时useNuxtApp().$pb的类型将正确识别为PocketBase。

内容的提问来源于stack exchange,提问作者Seyrinian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 06:13:23