自动导入插件unplugin-auto-import/unplugin-vue-components

原文地址: devpress.csdn.net/vue/66cd509...

1. unplugin-auto-import(自动导入API)

安装: npm i -D unplugin-auto-import

配置:

ts 复制代码
// vite.config.ts
import AutoImport from 'unplugin-auto-import/vite'

export default defineConfig({
  plugins: [
    AutoImport({ /* options */ }),
  ],
})

options详细配置:

配置解析

  1. dirs: 目录下模块导出的自动导入。默认情况下,它只扫描目录下的一级模块,我们可以添加一些通配符来做筛选,限定到指定目录,或者到src 都可以做到自动引入,但是为了精确化查找,建议匹配越精准越好
ts 复制代码
 // 配置本地目录 自动引入
  dirs: ['./src/utils/**', './src/stores/**'],
 //dirs: ['./src/**'],
  1. dts: 生成相应.d.ts文件的文件路径。默认为""/在本地安装"typescript"时自动导入.d.ts。
ts 复制代码
 dts: './auto-imports.d.ts',
  1. imports: 需要全局引入的

示例

without

ts 复制代码
import { computed, ref } from 'vue'

const count = ref(0)
const doubled = computed(() => count.value * 2)

with

ts 复制代码
const count = ref(0)
const doubled = computed(() => count.value * 2)

without

ts 复制代码
import {f1} from '@/utils'
f1();

with

ts 复制代码
f1();

without

ts 复制代码
import {concat} from 'lodash';
console.log(concat([1, 2], [3]))

with

ts 复制代码
console.log(concat([1, 2], [3]))

without

ts 复制代码
import { useState } from 'react'

export function Counter() {
  const [count, setCount] = useState(0)
  return <div>{ count }</div>
}

with

ts 复制代码
export function Counter() {
  const [count, setCount] = useState(0)
  return <div>{ count }</div>
}

2. unplugin-vue-components( 自动导入组件)

安装

ts 复制代码
npm i -D unplugin-vue-components

配置

这里我测试了一下,就算什么也不写,Components默认会自动引入 /src/components下的文件

ts 复制代码
// vite.config.ts
import Components from 'unplugin-vue-components/vite'

export default defineConfig({
  plugins: [
    Components({ /* options */ }),
  ],
})

你也可以再配置一些想自动引入的组件

dirs: ['./src/components', './src/index/components'],

如果害怕组件重名,可以加一个directoryAsNamespace的选项,这样自动导入的组件名称 包含目录 ,就会防止命名冲突

options 里面可以添加一些配置

  • 三方组件,也可以在这里进行自动引入
ts 复制代码
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers';
 
Components({
  // vue-components 内置了前端主流的resolve element antd
  resolvers: [ElementPlusResolver()],
  dirs: ['src/components'],
  // 组件名称 包含目录 ,防止命名冲突
  directoryAsNamespace: true,
}),

示例

without

相关推荐
Lanwarf-前端开发1 小时前
Vue3 + Canvas/WebGL 雷达扫描可视化实战:PPI、RHI、VOL、SVOL 四种模式原理与实现
前端·javascript·vue.js·webgl
FRing032 小时前
vue3干货总结2(vue3生命周期、父子通信、模版引用、provide和inject)
开发语言·前端·vue.js·vue3
锋行天下3 小时前
langgraph 全栈项目(三)
前端·人工智能·后端
锋行天下4 小时前
langgraph 全栈项目(二)
前端·人工智能·后端
锋行天下5 小时前
langgraph全栈项目(一)
前端·人工智能·后端
叼烟扛炮6 小时前
[LangChain] 学习笔记(15):为什么你的重试没用——429、抖动、fallback 与熔断
java·服务器·前端
小码哥0686 小时前
智慧物业系统源码定制:公告发布范围与住户阅读记录设计
前端·javascript·vue.js·物业管理·物业系统·物业软件
泯泷9 小时前
Cloudflare 出手抢 Astro:前端框架之战,底层逻辑变了
前端·javascript·前端框架
狮子座的男孩11 小时前
html+css基础:31、响应式布局(媒体类型,媒体特性,运算符,常用阈值)
前端·css·经验分享·html·响应式布局·媒体类型/特性·常用阈值