Property $logger does not exist on type 'Store<RootState>'
のようなエラーが発生する。今回はvueインスタンスを拡張し、vueファイル(SFC)とstore内で
this.$xxx
にアクセスするための型定義の作り方について紹介する。プラグインを実装する
サンプルのためLoggerプラグインを実装する。
// /plugins/logger.ts
export class Logger {
private readonly isDev: boolean
constructor(env) {
this.isDev = env !== 'production'
}
info(...messages: any[]) {
if (this.isDev) {
console.log('[info]', ...messages)
}
}
warn(...messages: any[]) {
if (this.isDev) {
console.warn('[warn]', ...messages)
}
}
error(...messages: any[]) {
if (this.isDev) {
console.error('[error]', ...messages)
}
}
}
export default (_, inject) => {
inject('logger', new Logger(process.env.NODE_ENV))
}
Loggerクラスは単純なもので、consoleを拡張したもの。inject('logger', new Logger())
の部分は、vueインスタンスやstoreからthis.$logger
にアクセスするための関数だ。詳細はNuxt.jsのプラグイン#統合された注入を参照してほしい。プラグインを読み込む
// nuxt.config.ts
export default {
// ...
plugins: ['@/plugins/logger.ts'],
// ...
}
nuxt.config.ts
のpluginsに先ほど作成したLoggerのパスを指定する。これでSFCやstoreから
this.$logger
にアクセスできるようになるのだが、このままではthis.$logger
の型がわからずProperty $logger does not exist on type 'Store<RootState>'
のようなエラーになってしまう。型定義を作成する
// ./types/logger.d.ts
import { Logger } from '@/plugins/logger'
// vueインスタンス用
declare module 'vue/types/vue' {
interface Vue {
readonly $logger: Logger
}
}
// store用
declare module 'vuex' {
interface Store<S> {
readonly $logger: Logger
}
}
これでSFCやstore内で
this.$logger
の型定義を参照できるようになった。参考サイト
以上
written by @bc_rikko
0 件のコメント :
コメントを投稿