3-1 TypeScriptの導入
まずはTypeScriptに対応するために、以下のコマンドを実行しパッケージを導入する。
yarn add -D typescript @vue/cli-plugin-typescript
パッケージの概要
-
typescript
TypeScriptのコンパイラ -
@vue/cli-plugin-typescript
<script>タグにてlang="ts"が指定された際に、TypeScriptのコンパイルを挟むためのパッケージ
3-2 Typescriptコンパイラの設定
次にプロジェクトルートにtsconfig.json及びvue-shims.d.tsを作成する。
各ファイルの内容の概要
-
tsconfig.json
TypeScriptコンパイラの挙動の設定を行うためのファイル。 -
vue-shims.d.ts
.vueファイルをTypeScriptコンパイラが読み込んだ際に、どのような型として読み込めばよいのか、を定義するためのファイル。
tsconfig.json
{
"compilerOptions": {
"target": "esnext",
"module": "esnext",
"strict": true,
"importHelpers": true,
"moduleResolution": "node",
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"sourceMap": true,
"baseUrl": ".",
"types": [
"webpack-env"
],
"lib": [
"esnext",
"dom",
"dom.iterable",
"scripthost"
],
"paths": {
"@/*": [
"src/*"
]
}
},
"include": [
"src/**/*.ts",
"src/**/*.vue",
"tests/**/*.ts",
],
"exclude": [
"node_modules"
]
}
src/vue-shims.d.ts
declare module '*.vue' {
import type { DefineComponent } from 'vue'
const component: DefineComponent<{}, {}, any>
export default component
}
3-3 src配下をTypeScript用に置き換える
まず、src/main.jsのファイル名をsrc/main.tsに書き換えてみる。すると、Appがimportできない旨のエラーが出る。
これは、上記のsrc/vue-shims.d.tsでmodule名が.vueで終わる際はVueコンポーネントとして読み込むための定義をしているためである。
そのため、src/main.tsを以下の用に変更する。
src/main.ts
import { createApp } from 'vue'
import App from './App.vue'
createApp(App).mount('#app')