【前端探索】vite+vue3+js转为ts的详细步骤

3,523 阅读2分钟

Vue 引入 TypeScript

npm i ts-loader typescript tslint tslint-loader tslint-config-standard --save-dev

配置vite

vite.config.js后缀改成.ts

加入extensions,为了之后引入.ts的时候不用写后缀,也可以不加

resolve: {
    extensions: ['.js','.vue','.json','.ts'],
    alias: {
        '@': path.resolve(__dirname, './src'),
    }
}

添加 tsconfig.json

在根路径下创建tsconfig.json文件,tsconfig.json是 ts 编译器的配置文件,ts编译器可以根据它的信息,来对代码进行编译,include 用来指定那些 ts 文件需要被编译,references 使用项目引用,可以将一个项目作为另一个项目的依赖。

这里有一份参考的 tsconfig.json 配置,完成的配置请点击 tsconfig.json

我的配置如下

tsconfig.json

{
    "compilerOptions": {
    "target": "esnext",
    "useDefineForClassFields": true,
    "module": "esnext",
    "moduleResolution": "node",
    "strict": true,
    "jsx": "preserve",
    "sourceMap": true,
    "resolveJsonModule": true,
    "isolatedModules": true,
    "esModuleInterop": true,
    "lib": ["esnext", "dom"],
    "skipLibCheck": true,
    "paths": {
    "@/*": ["./src/*"]
    },
    "forceConsistentCasingInFileNames": false
    },
    "include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue", "./components.d.ts"],
    "references": [{ "path": "./tsconfig.node.json" }]
}

tsconfig.node.json

由于我的tsconfig.json使用了references,所以还要补充tsconfig.node.json文件

{
    "compilerOptions": {
    "composite": true,
    "module": "esnext",
    "moduleResolution": "node"
    },
    "include": ["vite.config.ts"]
}

解决main.js文件报错

先把.js后缀改成.ts

报错可能是'./App.vue'以及createApp(App)处有红色波浪线

在src目录下(与main.ts同级)创建一个文件env.d.ts

/// <reference types="vite/client" />

declare module '*.vue' {
    import type { DefineComponent } from 'vue'
    const component: DefineComponent<{}, {}, any>
    export default component
}

波浪线消失!

改造routes.ts文件(非必要)

如果你也是使用了vue-router,修改如下

import { RouteRecordRaw } from "vue-router"

const routes: RouteRecordRaw[] = [
 ...
]

改造vue文件

<script setup lang="ts">

* 为ref加入<string>类型后后项目能运行,但是ref变量赋值的时候.value有红色波浪线

报错信息——不能将类型“RouteRecordName | null | undefined”分配给类型“string”。不能将类型“undefined”分配给类型“string”。

解决方法如下

可以通过类型断言 或者 类型判断 进行处理 (两种方法选其一)

  • 类型断言 类型断言,可以用来告诉解析器变量的实际类型

    path.value = router.currentRoute.value.name as string
    
  • 类型判断

    if (typeof (outer.currentRoute.value.name) === 'string') {
       path.value = router.currentRoute.value.name
    }
    

* 在ts中无法使用[]运算符获取某个Object对象中的指定属性的值

blog.csdn.net/qq_27962839…