【问题标题】:How to add typescript to Vue 3 and Vite project如何将打字稿添加到 Vue 3 和 Vite 项目
【发布时间】:2020-12-22 17:51:15
【问题描述】:

我的设置:我通过 create-vite-app 模块安装了 Vue 和 Vite,然后将 'init vite-app' 生成的所有包更新为最新的 RC 版本Vue 和 Vite。

现在我想为我的所有代码使用打字稿。首先我只是玩了一下,然后将 lang="ts" 添加到 HelloWorld.vue 的标签中。这似乎可行,虽然我不知道打字稿是如何从 vue 文件中转译出来的。

然后我尝试将 main.js 重命名为 main.ts。现在什么都没有发生。

我在想我只需要安装打字稿,但后来它打我,为什么它在 .vue 组件中工作呢?如果我现在安装 typescript,我做错了吗?

为什么typescript在vue模块(HelloWorld)中可以工作,但是*.ts文件没有生成js?

【问题讨论】:

  • 我会使用git clone https://github.com/ktsn/vite-typescript-starter.git,而不是create-vite-app,它使用最新版本的Vue 3 和Vite。
  • 谢谢,这很有帮助。这也证实了对主要问题的简短回答是,是的,只需安装 typscript,然后在编码时运行 tsc -w。

标签: typescript vue.js vite


【解决方案1】:

如何将 typescript 添加到 Vue 3 和 Vite 项目中

我将创建一个 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
  }
}

你可以在这里查看,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;
}

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创建您的组件文件
祝你好运!

【讨论】:

【解决方案2】:

有一个名为vue-ts 的打字稿模板。 所以运行npm init vite@latest my-vue-app -- --template vue-ts 设置了一个typescript vite 项目。

https://vitejs.dev/guide/#scaffolding-your-first-vite-project

更新:反映了 Olanrewaju 的评论。

【讨论】:

  • @vitejs/create-app 已弃用,请改用 npm init vite
【解决方案3】:

根据最新的docs,您可以运行以下命令之一,您可以选择框架和打字稿选项:

npm init vite@latest

yarn create vite

pnpm dlx create-vite

【讨论】:

    猜你喜欢
    • 2019-05-27
    • 2021-10-27
    • 2021-07-30
    • 2022-08-11
    • 2018-08-18
    • 2021-08-25
    • 2018-06-13
    • 2021-08-30
    • 2018-12-21
    相关资源
    最近更新 更多