【vue3+typescript】常见错误总结

1,244 阅读1分钟

1.组件props报错对象可能为空

<script lang="ts" setup>
import { Activity } from '@/typings/activity'

interface Props {
  activity: Activity | null
}

withDefaults(defineProps<Props>(), {
  activity: null
})
</script>

解决:在组件的根节点增加v-if不为空判断

<div v-if="activity" class="spell-group-item">

2.api.now is not a function

629e166c09314c2c10120280.jpg 解决: 和vue devtools有关系,重新禁用启用,或者重新安装

3.Component name "index" should always be multi-word

要求组件名称以驼峰格式命名。但实际开发时,一般页面组件我们以index命名,组件才以驼峰格式命名。
解决如下: 在.eslintrc.cjs文件中,增加vue/multi-word-component-name配置 1664243988454.png

4."XXX" 是一种类型,在同时启用了 "preserveValueImports" 和 "isolatedModules" 时,必须使用仅类型导入进行导入。

报错代码

import fetch, { RequestConfigOptions } from "@/utils/request";

原因是在同一个文件中,同时导入类型和值
解决方案有两种:

  • 修改配置文件tsconfig.json(我使用后未生效)
"compilerOptions": {
    "preserveValueImports":false
  },
  • 修改导入方式:
import type { RequestConfigOptions } from "@/utils/request";
import fetch from "@/utils/request";

5.模块的默认导出具有或正在使用专用名称“Props”

报错代码:

interface Props {
  menu: RouteRecordRaw
}
const props = defineProps<Props>()

解决:

const props = defineProps<{
  menu: RouteRecordRaw
}>()
export interface Props {
  menu: RouteRecordRaw
}
const props = defineProps<Props>()

原因:interface Props导出为默认模块了

6.配置别名时报找不到模块“path”或其相应的类型声明

第一步 配置vite.config.ts

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  resolve:{
    alias:[
      {
        find:'@',
        replacement:resolve(__dirname,'src')
      }
    ]
  }
})

第二步 在tsconfig.node.json中配置paths和baseUrl

{
  "compilerOptions": {
    "composite": true,
    "module": "ESNext",
    "moduleResolution": "Node",
    "allowSyntheticDefaultImports": true,
    "baseUrl": "./",
    "paths": {
      "@/*":["src/*"]
    }
  },
  "include": ["vite.config.ts","src/**/*.ts","src/**/*.vue"]
}

7.仅当 “--module” 选项为 “es2020”、“es2022”、“esnext”、“system”、“node16” 或 “nodenext” 时,才允许使用 “import.meta” 元属性。

在tsconfig.app.json,tsconfig.config.json,tsconfig.vitest.json文件的compilerOptions选项中增加"module": "ESNext"


持续更新中...