- Install the necessary dependencies
- Add TypeScript configuration files
- Add scripts
- Change file extensions
- Refactor the components
Suppose you have created a Vue 3 project with the command npm create vue@latest
and it is not integrated with TypeScript yet.
Install the necessary dependencies
To use TypeScript, we will need to need a few dependencies:
1 | npm i -D @tsconfig/node20 @types/node @vue/tsconfig npm-run-all2 vue-tsc typescript |
Add TypeScript configuration files
We need to add a tsconfig.json
file in the root directory of the project. You can generate a basic one by running:
1 | npx tsc ---init |
Vue has a package called @vue/tsconfig
, which contains the configuration files specific for Vue projects.
Based on this package, we can write like this in tsconfig.json
:
1 | { |
tsconfig.node.json
:
1 | { |
tsconfig.app.json
:
1 | { |
env.d.ts
:
1 | /// <reference types="vite/client" /> |
Add scripts
Edit package.json
then add or edit the following scripts:
1 | { |
Change file extensions
Rename vite.config.js
and main.js
to vite.config.ts
and main.ts
respectively.
Refactor the components
Options API
To let TypeScript properly infer types inside component options, we need to define components with defineComponent()
:
1 | import { defineComponent } from "vue"; |
Composition API
To use TypeScript in SFCs, add the lang="ts"
attribute to <script>
tags.
1 | <script setup lang="ts"> |
Now try running the project:
1 | npm run dev |