关于typescript改造旧项目的一些坑


‘@/‘ 引入组件报红问题

  • 使用 ‘@/xxx/xxx’ 引入组件,vetur报红 找不到module,但是可以正常运行问题
  • 解决办法:1.把项目目录放工作区根目录;2.项目一定排列在第一位

    引入第三方包报红

  • 引入第三方库 报红找不到module,无法正常使用包,如qs、jQuery
  • 解决办法1:使用@types进行包管理,然后正常引入
    npm i @types/qs
    import qs from 'qs'
  • 解决办法2:有些包不能用@types管理,自己写声明 XX.d.ts 不推荐

router配置里引入component组件的时候必须添加.vue后缀

Element表单验证报红问题

// 报错信息如下
// Property 'validate' does not exist on type 'Vue | Element | Vue[] | Element[]'.
// Property 'validate' does not exist on type 'Vue'.

// 解决办法
import { Form } from "element-ui";
( this.$refs.loginForm as Form ).validate((valid: boolean ) => {
  ...
 });

// 如果不引入Form,把Form换成any也可以,但是typescript会报警告⚠
  • 使用axios封装的请求,然后解构请求结果报错
    // 报错信息
    // Property 'XXX' does not exist on type 'AxiosResponse<any>'
    
    // 解决办法
    // 新建axios.d.ts文案,添加如下内容,重启项目
    import * as axios from 'axios'
    
    declare module 'axios' {
      interface AxiosInstance {
        (config: AxiosRequestConfig): Promise<any>
      }
    }
    @typescript/esline 报错 xxx_x is not in camel case

    关闭esline驼峰校验

    // 在.eslinetrc.js中配置如下:
    rules: {
      ...
      '@typescript-eslint/camelcase': 'off',
    }

    TS使用”require”报错

  • 提示报错信息:Cannot find name ‘require’. Do you need to install type definitions for node? Try ‘npm i –save-dev @types/node’
  • 解决方案:
    • 1.安装@types/node,npm i –save-dev @types/node;
    • 2.在tsconfig.json中的compilerOptions中的types添加”node”;
    • 3.在使用require前面添加declare var require:any

      TS使用”this.xxx”报错

      // 使用"this.$router.push("/xxx")" => Property '$router' does not exist on type 'Experiment'.
      // 解决:
      (this as any).$router.push("/xxx")
      this.$refs.mainVideo => Property 'clientWidth' does not exist on type 'Vue | Element | Vue[] | Element[]'.
      // Property 'clientWidth' does not exist on type 'Vue'
      // 解决:
      (this.$refs.mainVideo as any).clientWidth

文章作者: Damao
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Damao !
  目录