My setup: I installed Vue and Vite via the create-vite-app module, and then updated all the packages that was generated by 'init vite-app' to the very latest RC versions for Vue and Vite.
Now I want to use typescript for all my code. First I just played around a little bit, and added the lang="ts" to the tag in HelloWorld.vue. That seems to work, though I have no idea how typescript gets transpiled from the vue file though.
Then I tried to rename the main.js to main.ts. Now nothing happen.
I was thinking that I just need to install typescript, but then it hit me, why is it working in the .vue component then? Am I doing something wrong if I install typescript now?
Why does typescript work in the vue module (HelloWorld), but no js is generated from the *.ts file?
Actually, you can also implement TypeScript one file at the time with Vue (if you add it to an existing project). You take one of your Vue files and add the lang="ts" inside the script tag. Then you modify your component to use the Class API and fix the potential errors TypeScript found. It's really easy!
Now, you should be able to get your Vue app up and running in TypeScript with features like defineComponent , data, props, computed properties, methods, and watchers. Vue 3.0 includes better support for TypeScript out of the box, and the entire Vue code was rewritten in TypeScript to improve maintainability.
But how to make it work with an existing Vue3 Typescript Project? First you want to install Vite along with @vitejs/plugin-vue as developer dependencies. After that, you need to add "dev": "vite" to the scripts { .. } object in package.
I will create a vite project to use typescript step by step:
$ npm init vite-app <project-name>
$ cd <project-name>
$ npm install
$ npm install typescript
tsconfig.json
file in the root folder, like this:{
"compilerOptions": {
"target": "esnext",
"module": "esnext",
"moduleResolution": "node",
"importHelpers": true,
"isolatedModules": true,
"noEmit": true
}
}
And you can check here, What is a tsconfig.json
shims-vue.d.ts
file in the src
folder, like this:declare module "*.vue" {
import { defineComponent } from "vue";
const Component: ReturnType<typeof defineComponent>;
export default Component;
}
The shims-vue.d.ts
file helps your IDE to understand what a file ending in .vue
is.
Now, we can check whether the .ts
file works well.
In my case, i rename the main.js
file to main.ts
in the src
folder,
and modify the index.html
, 12 line:
<script type="module" src="/src/main.js"></script>
to
<script type="module" src="/src/main.ts"></script>
At last, run
npm run dev
If there is no error message, you can create your component file by .ts
Good luck!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With