Typescript+Nuxt环境下@nuxtjs/i18n类型不生效问题如何解决?
@nuxtjs/i18n Typescript 类型报错修复方案
1. 确认版本与基础配置匹配
- 如果你使用的是 Nuxt 2 + @nuxtjs/i18n v7.x 版本,原tsconfig配置的
compilerOptions.types项是正确的 - 如果你使用的是 Nuxt 3 + @nuxtjs/i18n v8.x 及以上版本,无需手动在types配置中添加声明,模块会自动注入类型,可先删除tsconfig中对应的
@nuxtjs/i18n类型引入再测试
2. 新增全局类型声明补全
如果版本匹配仍有报错,在项目根目录新建types/i18n.d.ts类型声明文件,根据你使用的Nuxt版本添加对应内容:
Nuxt 2 配置
import Vue from 'vue' import { NuxtI18nInstance, NuxtI18nLocale } from '@nuxtjs/i18n' declare module 'vue/types/vue' { interface Vue { $i18n: NuxtI18nInstance } } // 如果你自定义了locales配置的字段,可扩展类型避免报错 declare module '@nuxtjs/i18n' { interface NuxtI18nLocale { code: string name: string // 补充你自定义的其他字段 } }
Nuxt 3 配置
import { NuxtI18nInstance, NuxtI18nLocale } from '@nuxtjs/i18n' declare module '@vue/runtime-core' { interface ComponentCustomProperties { $i18n: NuxtI18nInstance } } // 自定义locales字段扩展同上
3. 更新tsconfig包含规则
在tsconfig.json的include配置项中添加你新增的类型声明文件路径,确保TS能识别到自定义声明:
{ "compilerOptions": { "types": [ "@nuxt/types", "@nuxtjs/i18n" ] }, "include": [ "types/**/*.d.ts", "**/*.vue", "**/*.ts" ] }
4. 重启TS服务
修改完类型配置后,在编辑器中执行重启TS服务操作:
- VSCode:按下
Ctrl/Command + Shift + P,选择TypeScript: Restart TS Server - 其他编辑器同理,重启编辑器或TS校验服务即可生效
内容的提问来源于stack exchange,提问作者morteza mortezaie
相关产品推荐
相关产品推荐

