如何将 TypeScript 添加到 Vue 3 和 Vite 项目中
我将逐步创建一个使用 TypeScript 的 Vite 项目:
$ 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
- 然后,在
src
文件夹中创建一个叫做 shims-vue.d.ts
的文件,像这样:
declare module "*.vue" {
import { defineComponent } from "vue";
const Component: ReturnType<typeof defineComponent>;
export default Component;
}
shims-vue.d.ts
文件帮助你的IDE理解以.vue
结尾的文件。
现在,我们可以检查.ts
文件是否工作正常。
在我的情况下,我将src
文件夹中的main.js
文件重命名为main.ts
,
并修改index.html
,第12行:
<script type="module" src="/src/main.js"></script>
到
<script type="module" src="/src/main.ts"></script>
最后,运行
npm run dev
如果没有错误提示,你可以通过.ts
创建你的组件文件。
祝你好运!
git clone https://github.com/ktsn/vite-typescript-starter.git
,而不是create-vite-app
。这个仓库使用了最新版本的 Vue 3 和 Vite。 - tony19