如何将typescript添加到Vue 3和Vite项目中
我将创建一个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
}
}
你可以在这里检查,什么是 tsconfig.json https://www.typescriptlang.org/docs/handbook/tsconfig-json.html
- 那么,我们应该创建一个
shims-vue.d.ts
文件在src
文件夹,像这样:
declare module "*.vue" {
import { defineComponent } from "vue";
const Component: ReturnType<typeof defineComponent>;
export default Component;
}
The shims-vue.d.ts
file 可以帮助您的 IDE 理解以什么结尾的文件.vue
is.
现在,我们可以检查是否.ts
文件运行良好。
就我而言,我重命名main.js
文件到main.ts
in the src
folder,
并修改index.html
,12行:
<script type="module" src="/src/main.js"></script>
to
<script type="module" src="/src/main.ts"></script>
最后,运行
npm run dev
如果没有错误消息,您可以通过以下方式创建组件文件.ts
祝你好运!