2018.11.28
vue + TypeScriptのプロジェクトで、定義ファイルの無いライブラリに対応する。
この記事ではvue-analytics。
https://github.com/MatteoGabriele/vue-analytics
https://github.com/MatteoGabriele/vue-analytics/issues/161
issueは上がってるけどPRもまだない。自前でPR出せるくらい対応できるならいいんだけど、時間もないので取り敢えずコンパイル通る様にしたい場合。
前提
$ vue create ts-project
# TypeScript対応以外は適当
# vue-cli3, vue2.5.17, typescript3.1.6
対応
- tsconfig.jsonに1行追加
tsconfig.json
~~ 省略
"paths": {
"@/*": ["src/*"],
+ "vue-analytics": ["src/types/vue-analytics"]
},
~~ 省略
- type定義ファイル追加
src/types/vue-analytics.d.ts
import _Vue, { PluginFunction } from 'vue';
declare class VueAnalytics {
static install(Vue: typeof _Vue, options: any): void;
analyticsMiddleware: any;
onAnalyticsReady: any;
event: any;
ecommerce: any;
set: any;
page: any;
query: any;
screenview: any;
time: any;
require: any;
exception: any;
social: any;
}
export default VueAnalytics;
declare module 'vue-analytics' {
}
declare module 'vue/types/options' {
interface ComponentOptions<V extends _Vue> {
ga?: VueAnalytics;
}
}
declare module 'vue/types/vue' {
interface Vue {
$ga: VueAnalytics;
}
}
あとは通常通り使う。
// main.ts
import Analytics from 'vue-analytics';
Vue.use(Analytics, {/*options*/});
// in components
this.$ga.event('category', 'action', 'label', 123);
必要に応じてsrc/types/vue-analytics.d.ts
に定義を付け足す。
vue-analyticsが正式にサポートしたら、定義ファイルとtsconfig.jsの1行を削除して、プロジェクトの定義ファイル(shims-vue.d.ts
とか)で、import 'vue-analytics';
とかしとけばok