• ant design vue 实现组件类型推断 vue3,vite,ts


    1,全局引入的antd vue组件是没有代码提示的

    因为全局引入的时候组件的类型已经丢失了,这时候写代码就没有这个组件的代码提示,还得去看文档

     2,如何实现全局组件类型推断

       (1),在使用的时候引入,这个不用多说,使用的时候写import就行

       (2),在全局写一个类型定义文件,这个需要使用vite的插件帮我们实现

    3,实现推断

    (1),使用vite的unplugin-vue-components插件帮我们实现Vue 的按需组件自动导入

    https://github.com/antfu/unplugin-vue-components

    (2),配置 vite.config.ts

    安装完成unplugin-vue-components后配置如下:

    1. import Components from "unplugin-vue-components/vite"; // 按需组件自动导入
    2. import { AntDesignVueResolver } from "unplugin-vue-components/resolvers";
    3. // https://vitejs.dev/config/
    4. export default ({
    5. mode,
    6. }: {
    7. mode: "dev" | "prod" | "build" | "devbuild";
    8. }): UserConfigExport => {
    9. return defineConfig({
    10. plugins: [
    11. vue(),
    12. vueJsx(),
    13. Components({
    14. dts: true, //生成components.d.ts 全局定义文件
    15. resolvers: [
    16. AntDesignVueResolver({ //对使用到的全局ant design vue组件进行类型导入
    17. importStyle: false, // 不动态引入css,这个不强求
    18. }),
    19. ],
    20. include: [/\.vue$/, /\.vue\?vue/, /\.md$/, /\.tsx$/], //包含的文件类型
    21. })
    22. ],
    23. ....其他配置
    24. });
    25. };

     (3),再次启动项目时会自动生成一个components.d.ts

     (4),有这个文件还不够,还需要在tsconfig.json配置文件中修改配置,使得vscode能正确识别类型

    1. {
    2. "compilerOptions": {
    3. "target": "esnext",
    4. "module": "esnext",
    5. "moduleResolution": "node",
    6. "strict": true,
    7. "jsx": "preserve",
    8. "sourceMap": true,
    9. "resolveJsonModule": true,
    10. "esModuleInterop": true,
    11. "types": ["vite/client","node"],
    12. "baseUrl": ".",
    13. "importHelpers": true,
    14. "skipLibCheck": true,
    15. "allowSyntheticDefaultImports": true,
    16. "paths": {
    17. "@/*": ["src/*","components.d.ts"],
    18. },
    19. "lib": [
    20. "esnext",
    21. "dom",
    22. "dom.iterable",
    23. "scripthost"
    24. ]
    25. },
    26. "exclude": [
    27. "node_modules"
    28. ],
    29. "include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue","main/**/*"]
    30. }

    (5)这时候就可以使用类型推断了,enjoy

     

  • 相关阅读:
    MySQL 与 PostgreSQL的区别
    Webpack设置代码映射,可调试打包后的代码
    Halcon知识:三维重构的一个尝试
    【0234】PgBackendStatus 记录当前postgres进程的活动状态
    OnePose: 无CAD模型的one-shot物体姿态估计(CVPR 2022)
    日志框架log4j升级至log4j2
    【MySQL】库的操作——MySQL数据库 、库的操作、表的操作、字符集和校验规则、备份和恢复
    单例模式(懒汉式、饿汉式)
    VMware安装Centos
    类欧笔记存档
  • 原文地址:https://blog.csdn.net/qq_32674347/article/details/125618616