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后配置如下:
- import Components from "unplugin-vue-components/vite"; // 按需组件自动导入
- import { AntDesignVueResolver } from "unplugin-vue-components/resolvers";
- // https://vitejs.dev/config/
- export default ({
- mode,
- }: {
- mode: "dev" | "prod" | "build" | "devbuild";
- }): UserConfigExport => {
- return defineConfig({
- plugins: [
- vue(),
- vueJsx(),
- Components({
- dts: true, //生成components.d.ts 全局定义文件
- resolvers: [
- AntDesignVueResolver({ //对使用到的全局ant design vue组件进行类型导入
- importStyle: false, // 不动态引入css,这个不强求
- }),
- ],
- include: [/\.vue$/, /\.vue\?vue/, /\.md$/, /\.tsx$/], //包含的文件类型
- })
- ],
- ....其他配置
- });
- };
(3),再次启动项目时会自动生成一个components.d.ts

(4),有这个文件还不够,还需要在tsconfig.json配置文件中修改配置,使得vscode能正确识别类型
- {
- "compilerOptions": {
- "target": "esnext",
- "module": "esnext",
- "moduleResolution": "node",
- "strict": true,
- "jsx": "preserve",
- "sourceMap": true,
- "resolveJsonModule": true,
- "esModuleInterop": true,
- "types": ["vite/client","node"],
- "baseUrl": ".",
- "importHelpers": true,
- "skipLibCheck": true,
- "allowSyntheticDefaultImports": true,
- "paths": {
- "@/*": ["src/*","components.d.ts"],
- },
- "lib": [
- "esnext",
- "dom",
- "dom.iterable",
- "scripthost"
- ]
- },
- "exclude": [
- "node_modules"
- ],
- "include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue","main/**/*"]
- }
(5)这时候就可以使用类型推断了,enjoy
