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

现在我想对所有代码使用typescript.首先,我只是玩了一会儿,在HelloWorld.vue的标签上加了lang="ts".这似乎是可行的,不过我不知道typescript是如何从vue文件传输过来的.

然后我试着把main.js改成main.ts.现在什么都没发生.

我想我只需要安装typescript,但我突然想到,为什么它在.vue组件中工作?如果我现在安装typescript,我是不是做错了什么?

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

推荐答案

How 到 add typescript 到 Vue 3 and Vite project

我将创建一个vite项目,逐步使用typescript:

  • 首先,我们应该首先创建一个vite项目
$ npm init vite-app <project-name>
$ cd <project-name>
$ npm install
  • 其次,我们应该安装typescript
$ 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!

Vue.js相关问答推荐

Vue 3 需要 main.js 中的文件

VSelect - Select 不适用于 Vuetify 3 中的自定义项目插槽

使用 vue / nuxt js 切换 fontawesome 图标

如果单元格不可见,则以编程方式打开行的编辑模式. Ag 网格,Vue.js

Vuetify/Nuxt 生产环境组件在开发环境中无法正常工作

Defer推迟执行,直到外部脚本加载到 Vue.js

如何在 vue.js 构建中重命名 index.html?

如何将 vue.js 与 gulp 一起使用?

Vue.js 从模板中分离样式

命名空间模块身份验证的重复命名空间身份验证

Vue-test-utils:在单个测试中多次使用 $nextTick

vue js 中的 process.env.BASE_URL 是什么?

Vue CLI - 将构建输出组合到单个 html 文件

为 Vue 组件动态添加属性

如何告诉 Vue-cli 我的应用程序的入口点在哪里?

异步api调用后如何使用vuex getter

vue-router如何持久化导航栏?

依赖关系甚至在 package.json 和 node_modules 中都没有定义

Vuetify - 如何进行分页?

表格行上的 Vuejs 转换