0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Nuxt.jsでpluginを快適に運用する( 型定義ファイルの実装)

Posted at

Nuxt with jsで開発しているとき、例えば下記のような ~/plugins/api.js を実装したい。

~/plugins/api.js
export default function ({ }, inject) {
  const api = new API()

  inject('api', api)
}

class API {
  executeSomething() {
    return 'Hello world!'
  }
}

このAPIプラグインを ~/nuxt.config.js に登録し、

~/nuxt.config.js

// 中略
  plugins: [
    { src: './plugins/api.js' }
  ]

pagesとかで使おうとすると...補完が効かない。

スクリーンショット 2021-01-31 19.18.13.png

対応策

  1. ~/plugins/api.d.ts を作成
~/plugins/api.d.ts
export declare interface api {
  executeSomething(): String
}
  1. プロジェクトrootに index.d.tsを作成
~/index.d.ts
import Vue from 'vue'
import { api } from './plugins/api'

declare module 'vue/types/vue' {
  interface Vue {
    $api: api
  }
}

わーい🙌

スクリーンショット 2021-01-31 19.21.43.png

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?