unplugin-auto-import自动导入TS2304警告问题

在Vite配置中使用AutoImport插件自动导入ElementPlus和其它库,并通过tsconfig.json引入auto-imports.d.ts来解决TS2304错误。详细步骤包括在vite.config.js中设置插件,生成类型声明文件,以及更新tsconfig.json的include字段。
摘要由CSDN通过智能技术生成

1.前置配置

通过vite.config.js配置自动导入API

export default defineConfig({
	plugins: [
		vue(),
		AutoImport({
			resolvers: [ElementPlusResolver()],
			imports: ['vue', 'vue-router', 'pinia'],
			eslintrc: {
				enabled: false,
				filepath: './.eslintrc-auto-import.json',
				globalsPropValue: true,
			},
		})
	]
})

生成文件:auto-imports.d.ts

2. TS2304

此时代码中编写时会遇到TS的警告。Cannot find name 'ref'.ts(2304)
在这里插入图片描述

3.解决方案

ts.config.json文件引入声明文件: include中引入auto-imports.d.ts

{
  "compilerOptions": {
    "target": "esnext",
    "useDefineForClassFields": true,
    "module": "esnext",
    "moduleResolution": "node",
    "strict": true,
    "jsx": "preserve",
    "sourceMap": true,
    "resolveJsonModule": true,
    "esModuleInterop": true,
    "lib": ["esnext", "dom"]
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.d.ts",
    "src/**/*.tsx",
    "src/**/*.vue",
    "auto-imports.d.ts" // 此处引入该声明文件
  ],
  "references": [{ "path": "./tsconfig.node.json" }]
}
  • 10
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 8
    评论
unplugin-auto-import 是一个用于自动导入模块的 Vite 插件,可以帮助我们快速导入组件、函数、变量等等。以下是在 Vue 3 + TypeScript 项目中使用 unplugin-auto-import 自定义导入路径的步骤: 1. 安装所需依赖: ```bash npm install -D vite-plugin-auto-import ``` 2. 在构建配置中添加插件,并配置自定义导入: ```javascript import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' import AutoImport from 'unplugin-auto-import/vite' export default defineConfig({ plugins: [ vue(), AutoImport({ // 配置需要自动导入的模块 imports: [ { // 导入组件 path: 'vue', // 定义导入名称 imports: ['defineComponent'], }, { // 导入自定义组件 path: '@/components/MyCustomComponent.vue', // 定义导入名称 imports: ['MyCustomComponent'], }, { // 导入函数 path: 'lodash/debounce', // 定义导入名称 imports: ['debounce'], }, { // 导入变量 path: '@/config', // 定义导入名称 imports: ['appConfig'], }, ], }), ], }) ``` 3. 在代码中使用自定义导入的模块: ```vue <template> <MyCustomComponent /> </template> <script lang="ts"> import { defineComponent } from 'vue' import { debounce } from 'lodash' import { appConfig } from '@/config' import { MyCustomComponent } from '@/components/MyCustomComponent.vue' export default defineComponent({ components: { MyCustomComponent, }, data() { return { searchText: '', } }, methods: { search: debounce(() => { console.log('searchText:', this.searchText) }, 500), }, }) </script> ``` 注意:在使用 unplugin-auto-import 插件时,需要在 tsconfig.json 文件中开启 "esModuleInterop": true,以支持模块导入
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值