vue3 + ts项目(无vite)报错记录

记录项目创建后遇到的报错
1.类型“Window & typeof globalThis”上不存在属性“_CONFIG”。ts(2339)

问题描述:

使用全局 window 上自定义的属性,TypeScript 会报属性不存在
在这里插入图片描述

解决:需要将自定义变量扩展到全局 window 上,在项目的xxx.d.ts文件添加如下代码声明

declare interface Window {
  _CONFIG: any
}

添加后好像得重启编译器

2.axios报错
2.1 问题描述:

在这里插入图片描述
这个报错是因为axios版本更新后出现了新的类型导致的问题,可以根据此贴中的描述来解决,也可以用回旧版本解决,我是用回了0.21.x的旧版本

yarn add axios@^0.21.1
2.2 类型“AxiosResponse”上不存在属性“success”。ts(2339)

在这里插入图片描述

解决:封装文件中追加声明描述

import axios, { AxiosRequestConfig, AxiosResponse, AxiosError } from 'axios'

declare module "axios" {
  interface AxiosResponse<T = any> {
    result:any
    success:any,
    // 这里追加你的参数
  }
  export function create(config?: AxiosRequestConfig): AxiosInstance;
}
3.vue.config.js路径别名配置
module.exports = defineConfig({
  transpileDependencies: true,
  lintOnSave: false,
  publicPath: "/",
  outputDir: "dist",
  chainWebpack: config => {
    config.resolve.alias
      .set('@', resolve('src'))
      .set('@assets', resolve('src/assets'))
      .set('@views', resolve('src/views'))
      .set('@comp', resolve('src/components'))
  }
});
4.项目引入第三方库的关键字报错

问题描述:
在这里插入图片描述
这里就是第三方库的关键字DC报错了

解决:还是在xxx.d.ts文件中追加关键字声明

declare var DC: any
5.全局函数或全局变量注册

在main.ts文件中

//引入全局函数
import isLogin from './utils/utils'

const app = createApp(App)

app.config.globalProperties.$isLogin = isLogin

在页面中使用

//模板
<div >
      {{ $isLogin() ? "用户": "登录" }}
    </div>

//语法糖
<script setup lang="ts">
import { reactive, ref, getCurrentInstance } from "vue"; 

const { proxy } = getCurrentInstance();
console.log("proxy", proxy.$isLogin());

然后页面报了一个错误
在这里插入图片描述
需要在项目中新建一个xxx.d.ts文件,添加以下代码


export {}
declare module 'vue' {
    interface ComponentCustomProperties {
      $isLogin: any
    }
  }

参考:TypeScript 与选项式 API | Vue.js

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值