2019/04/15

Nuxt.js+TypeScriptでプラグインの型定義を作成する

Nuxt.jsには簡単にプラグインを追加できる仕組みがある。createdやmothodsなどを拡張するmixinタイプや、ElementUIなどコンポーネントタイプ、vueインスタンスにコンテキストを注入してthisを拡張するタイプなどがあるのだが、TypeScriptと併用すると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 件のコメント :

コメントを投稿