【Vue】Vueプラグイン + TypeScript ~ 入門編 ~

■ はじめに

フロントエンドのログで、console.log() 以外に何があるのって
話題になって、console.debug/info/warn/errorもあることが分かった。

https://developer.mozilla.org/ja/docs/Web/API/console#methods

Vueを使っているので、vuejs-logger っていう以下のサイト

https://openbase.io/categories/js/best-vue-logging-libraries?orderBy=RECOMMENDED&

で一番人気ありそうなロガーをはじめ挑戦しようとしたら
設定途中でエラー(※)になったので、Vueプラグインを使って、
独自で実装することを考えてみた。
TypeScript で Vueプラグイン を実装するサンプルがあまりないのでその辺もメモ。

※ vuejs-logger のエラーについて

以下のIssueが関連しそう。

https://github.com/justinkames/vuejs-logger/issues/33

ただ、いくらトラブルシュートできたとしても、
こんなに不安定だとバージョンを上げたら動かなくなりそうなので
調査を途中で打ち切った。

目次

【1】Vueプラグイン
【2】サンプル

【1】Vueプラグイン

https://dk521123.hatenablog.com/entry/2020/12/24/000000

で取り扱った Vue Router などもプラグインに当たる。

どこでも使える便利ツールを追加できる機能。
詳細は、以下の公式サイトを参照。

https://jp.vuejs.org/v2/guide/plugins.html

【2】サンプル

今回は、VueプラグインをTypeScriptで
実装するHello world的なものを作るのが目的なので
console.debug/info/warn/errorをラップ+α しただけのものを
実装する。

ファイル構成

my-app << 対象プロジェクト
 + src
     + logger << 新規追加
      |  + Logger.ts << 新規追加
     + types << 新規追加
      |  + Logger.d.ts << 新規追加
     + views
      |  + Hello.vue << 新規追加
      + router
        + index.ts << 修正(Hello.vueを追加。今回は省略)

Logger.ts

import _Vue from 'vue';

// Refer to https://qiita.com/AyumuAyumu/items/68bd36dcc417cb602a7f
function toDateText(date: Date) {
  const yyyy = `${date.getFullYear()}`;
  const MM = `0${date.getMonth() + 1}`.slice(-2);
  const dd = `0${date.getDate()}`.slice(-2);
  const HH = `0${date.getHours()}`.slice(-2);
  const mm = `0${date.getMinutes()}`.slice(-2);
  const ss = `0${date.getSeconds()}`.slice(-2);
  return `${yyyy}/${MM}/${dd} ${HH}:${mm}:${ss}`;
}

export function log(
  loggerType: 'error' | 'warn' | 'info' | 'debug' | 'log',
  message: string) {
  const current = toDateText(new Date());
  const logContent = `[${current}] ${message}`;

  switch(loggerType) {
    case "error":
      console.error(logContent);
      break;
    case "warn":
      console.warn(logContent);
      break;
    case "info":
      console.info(logContent);
      break;
    case "debug":
      console.debug(logContent);
      break;
    default:
      console.log(logContent);
      break;
  }
}

export default {
  install(Vue: typeof _Vue): void {
    Vue.prototype.$log = {
      error(message: string) { log('error', message) },
      warn(message: string) { log('warn', message) },
      info(message: string) { log('info', message) },
      debug(message: string) { log('debug', message) },
      log(message: string) { log('log', message) }
    }
  }
};

Logger.d.ts (インタフェース定義)

import Vue from "vue";

declare module 'vue/types/vue' {
  interface Vue {
    $log: {
      error: (message: string) => void,
      warn: (message: string) => void,
      info: (message: string) => void,
      debug: (message: string) => void,
      log: (message: string) => void
    };
  }
}

Hello.vue

<template>
  <div>
    <div><button v-on:click="onClickForError">Click me! - Error</button></div>
    <div><button v-on:click="onClickForWarn">Click me! - Warn</button></div>
    <div><button v-on:click="onClickForInfo">Click me! - Info</button></div>
    <div><button v-on:click="onClickForDebug">Click me! - Debug</button></div>
    <div><button v-on:click="onClickForLog">Click me! - Log</button></div>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';

@Component
export default class VuexDemo extends Vue {
  mounted() {
    this.$log.info('component is mounted!');
  }

  onClickForError() {
    this.$log.error('Click - error');
  }
  onClickForWarn() {
    this.$log.warn('Click - warn');
  }
  onClickForInfo() {
    this.$log.info('Click - info');
  }
  onClickForDebug() {
    this.$log.debug('Click - debug');
  }
  onClickForLog() {
    this.$log.log('Click - log');
  }
}
</script>

動作確認

[1] 以下をコマンドし、サーバを起動させる
~~~~~
npm run server
~~~~~
[2] ブラウザ(今回は、Chrome)を開き、F12 等でデベロッパーツールを開く
[3] [2]の状態で以下のURLにアクセスする

http://localhost:8080/Hello

[4] ボタンを順番に押していく

出力結果

[2021/01/12 00:02:51] component is mounted!
[2021/01/12 00:02:52] Click - error
[2021/01/12 00:02:53] Click - warn
[2021/01/12 00:02:55] Click - info
[2021/01/12 00:02:56] Click - debug
[2021/01/12 00:02:56] Click - log

補足:Chromeでdebugログが表示されなかった場合
https://blog.yuhiisk.com/archive/2017/08/17/chrome-devtool-console.html

が参考になる。

 デベロッパーツールにおいて、
[All Levels]を選択し、[Verbose]にチェックを入れたら出た。

参考文献

https://qiita.com/gyarasu/items/6e446c4605672d150bf1
https://riptutorial.com/ja/vue-js/example/27220/%E3%82%B7%E3%83%B3%E3%83%97%E3%83%AB%E3%83%AD%E3%82%AC%E3%83%BC

関連記事

Vue ~ 入門編 ~
https://dk521123.hatenablog.com/entry/2020/04/30/000000
Vue Mixins + TypeScript ~ 入門編 ~
https://dk521123.hatenablog.com/entry/2021/01/13/110105
Vue Router ~ 入門編 ~
https://dk521123.hatenablog.com/entry/2020/12/24/000000