How to add typescript to vue 3 and vite project?

Member

by lily , in category: Javascript , 9 months ago

How to add typescript to vue 3 and vite project?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by lindsey.homenick , 9 months ago

@lily 

To add TypeScript to a Vue 3 project set up with Vite, follow these steps:

  1. Install TypeScript and vue-tsc in your project:
1
npm install --save-dev typescript vue-tsc


  1. Create a tsconfig.json file in the root of your project:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "moduleResolution": "node",
    "strict": true,
    "jsx": "preserve",
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "strictPropertyInitialization": false
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.d.ts"
  ]
}


  1. Rename your Vue files from .js to .ts and update the file content to TypeScript syntax.
  2. Update your vite.config.js file to add TypeScript support:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

export default defineConfig({
  plugins: [vue()],
  server: {
    hmr: {
      protocol: 'ws',
      host: 'localhost'
    }
  },
  resolve: {
    alias: {
      '@': require('path').resolve(__dirname, 'src')
    },
  }
})


  1. Update your main.ts file to import Vue and create the app instance:
1
2
3
4
import { createApp } from 'vue'
import App from './App.vue'

createApp(App).mount('#app')


  1. Run the Vite development server:
1
npm run dev


Your Vue 3 project with TypeScript should now be set up and running with Vite.