How 到 add typescript 到 Vue 3 and Vite project
我将创建一个vite项目,逐步使用typescript:
$ npm init vite-app <project-name>
$ cd <project-name>
$ npm install
$ npm install typescript
- 第三,我们应该在根文件夹中创建一个
tsconfig.json
文件,如下所示:
{
"compilerOptions": {
"target": "esnext",
"module": "esnext",
"moduleResolution": "node",
"importHelpers": true,
"isolatedModules": true,
"noEmit": true
}
}
你可以在这里查What is a tsconfig.json
- 然后,我们在
src
文件夹中创建一个shims-vue.d.ts
文件,如下所示:
declare module "*.vue" {
import { defineComponent } from "vue";
const Component: ReturnType<typeof defineComponent>;
export default Component;
}
The shims-vue.d.ts
file helps your IDE 到 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 到 main.ts
in the src
folder,
and modify the index.html
, 12 line:
<script type="module" src="/src/main.js"></script>
到
<script type="module" src="/src/main.ts"></script>
最后,快跑
npm run dev
If there is no error message, you can create your component file by .ts
Good luck!