Vite插件v1.1.0发布:自动导入全面重构

版本:1.1.0 | 协议:MIT | 依赖:Vite >=5.0.0 <8.0.0


写在前面

v1.1.0 的主题是:autoImport 插件全面重构

对自动导入插件进行了从底层到 API 的全面重构,新增预设系统、多种导入形式、Lint 配置生成、缓存机制等核心能力,同时在目录扫描和 DTS 生成上做了增强。同时清理了旧版兼容类型(ImportMappingResolvedImport),统一为更灵活的 ImportInline 类型体系。

本版重点

能力 一句话说明 你需要做什么
内置预设系统 imports: ['vue', 'vue-router', 'pinia'] 一键配置 替换手动列举 API 的写法
别名/类型/命名空间导入 支持 as 别名、import typeimport * 等全形式 按需使用新格式
ESLint/Biome 配置生成 自动生成 globals 配置,解决 no-undef 报错 开启 eslintrcbiomelintrc
HMR 热更新 扫描目录文件变更自动刷新映射表 无需配置,自动生效
缓存机制 缓存预设解析与文件扫描结果,提升构建性能 默认启用
旧版类型清理 移除 ImportMappingResolvedImport 等废弃类型 迁移到新类型(见升级指南)

升级方式 :修改 devDependencies 中版本号为 ^1.1.0有少量 Breaking Change(仅影响使用了废弃类型的用户)。


一、5 分钟快速上手

1.1 安装与升级

json 复制代码
{
	"devDependencies": {
		"@meng-xi/vite-plugin": "^1.1.0"
	}
}

1.2 预设快速配置

typescript 复制代码
// vite.config.ts
import { defineConfig } from 'vite'
import { autoImport } from '@meng-xi/vite-plugin'

export default defineConfig({
	plugins: [
		// 1.0.0:手动列举每个 API
		// autoImport({ imports: { vue: ['ref', 'reactive', 'computed', 'watch', ...] } })

		// 1.1.0:使用内置预设,一行搞定
		autoImport({
			imports: ['vue', 'vue-router', 'pinia'],
			dts: 'src/auto-imports.d.ts',
			vueTemplate: true
		})
	]
})

1.3 新增导入形式

typescript 复制代码
autoImport({
	imports: [
		// 预设字符串
		'vue',

		// 别名导入:import { useFetch as useMyFetch } from '@vueuse/core'
		{ '@vueuse/core': ['useMouse', ['useFetch', 'useMyFetch']] },

		// 类型导入:import type { RouteLocationRaw } from 'vue-router'
		{ from: 'vue-router', imports: ['RouteLocationRaw'], type: true },

		// 命名空间导入:import * as _ from 'lodash'
		{ lodash: [['*', '_']] },

		// export assignment 导入:import browser from 'webextension-polyfill'
		{ 'webextension-polyfill': [['=', 'browser']] }
	]
})

二、Breaking Changes 与迁移指南

2.1 移除的废弃类型

移除项 替代方案 影响范围
ImportMapping 类型 使用 InlineImportConfig 或预设字符串 使用该类型的用户
ResolvedImport 类型 使用 ImportInline 使用该类型的用户
AutoImportOptions.fileFilter 使用 include / excludedirsScanOptions.fileFilter 使用该选项的用户
helpers/compat.ts 兼容模块 无需替代,旧格式不再支持 极少数直接引用

2.2 迁移示例

typescript 复制代码
// ❌ 1.0.0 旧写法(不再支持)
autoImport({
	imports: [{ module: 'vue', names: ['ref', 'reactive'], defaultImport: false }],
	fileFilter: /\.[tj]sx?$/
})

// ✅ 1.1.0 新写法
autoImport({
	imports: [
		'vue' // 或 { vue: ['ref', 'reactive'] }
	],
	include: [/\.[tj]sx?$/]
})

2.3 兼容性说明

  • imports: { vue: ['ref', 'reactive'] } Record 格式:仍支持,无需修改
  • imports: { vue: ['*'] } 通配符格式:仍支持 ,但推荐使用预设 'vue'
  • dirs 字符串数组格式:仍支持,无需修改
  • dts 字符串/boolean 格式:仍支持,新增 DtsConfig 对象格式

三、新增功能详解

3.1 内置预设系统

通过预设字符串一键启用常用库的自动导入,无需逐一列举 API:

预设名 模块 覆盖 API 数量 示例
vue vue 30+ ref、reactive、computed、watch、onMounted...
vue-router vue-router 15+ useRouter、useRoute、RouterLink...
pinia pinia 8+ defineStore、storeToRefs、createPinia...
vue-i18n vue-i18n 6+ useI18n、createI18n...
typescript 复制代码
// 预设字符串
autoImport({ imports: ['vue', 'vue-router', 'pinia'] })

// 预设与自定义混合
autoImport({ imports: ['vue', { '@vueuse/core': ['useMouse'] }] })

3.2 多种导入形式

导入形式 配置格式 生成语句
命名导入 { vue: ['ref'] } import { ref } from 'vue'
别名导入 { vue: [['ref', 'refVal']] } import { ref as refVal } from 'vue'
默认导入 { axios: [['default', 'axios']] } import { default as axios } from 'axios'
类型导入 { from: 'vue', imports: ['Ref'], type: true } import type { Ref } from 'vue'
命名空间导入 { lodash: [['*', '_']] } import * as _ from 'lodash'
export assignment { 'webext-polyfill': [['=', 'browser']] } import browser from 'webextension-polyfill'

3.3 目录扫描增强

typescript 复制代码
autoImport({
	dirs: [
		'./composables', // 仅扫描一级
		'./composables/**', // 递归扫描所有子目录
		{ glob: './hooks', types: true } // DirConfigObject,标记为类型导入
	],
	dirsScanOptions: {
		filePatterns: ['*.ts'], // Glob 文件匹配模式
		fileFilter: file => !file.endsWith('.test.ts'), // 自定义过滤
		types: false // 全局默认类型标记
	}
})

3.4 DTS 生成增强

typescript 复制代码
autoImport({
	dts: {
		filepath: 'src/auto-imports.d.ts',
		mode: 'append' // 'append' 仅追加新类型 | 'overwrite' 全量覆盖
	},
	dtsPreserveExts: false, // DTS 中是否保留文件扩展名
	ignoreDts: ['React'] // DTS 中排除指定标识符
})

3.5 ESLint / Biome 配置生成

解决自动导入标识符的 no-undef 报错:

typescript 复制代码
autoImport({
	imports: ['vue'],
	eslintrc: {
		enabled: true,
		filepath: './.eslintrc-auto-import.json',
		globalsPropValue: true // true = true | 'readonly' | 'writable'
	},
	biomelintrc: {
		enabled: true,
		filepath: './biome-auto-import.json'
	}
})

3.6 Vue 指令自动导入

typescript 复制代码
autoImport({
	imports: ['vue'],
	vueDirectives: {
		enabled: true,
		isDirective: fromPath => fromPath.includes('/directives/')
	}
})

3.7 其他新增功能

功能 配置 说明
缓存机制 cache: true(默认) 缓存预设解析与文件扫描结果,提升构建性能
HMR 热更新 自动启用 扫描目录文件变更时自动重新初始化映射表
注释禁用 // @unimport-disable 文件级或行级禁用自动导入
自定义 Resolver resolvers: [myResolver] 对未命中标识符自定义解析逻辑
包预设 packagePresets: ['@vueuse/core'] 从已安装包的 .d.ts 自动发现导出
Vite optimizeDeps 集成 viteOptimizeDeps: true 自动将依赖加入 Vite 预优化列表(默认关闭)
默认导出按文件名 defaultExportByFilename: true 目录扫描时默认导出使用文件名作为标识符

四、重构优化

优化项 1.0.0 1.1.0
Resolver 回退逻辑 仅当 usedImports 为空时触发 resolver 始终对未命中标识符尝试 resolver
DTS 生成 initialize()buildEnd 可能重复写入 dtsGeneratedInInit 标志避免冗余写入
解析引擎 多种格式分别处理 resolveImportsConfig 统一处理预设/Record/Inline 等
通配符导出解析 回退到运行时入口(可能不完整) 优先从 .d.ts 解析(最准确),回退到运行时入口
类型体系 ImportMapping + ResolvedImport 两套类型 统一为 ImportInline 单一类型
旧版兼容 compat.ts 处理旧格式转换 移除兼容层,仅支持新格式

五、配置选项完整对照

选项 1.0.0 1.1.0 说明
imports ✅ Record ✅ 增强 新增预设字符串、别名、类型导入等格式
dirs ✅ string\[\] ✅ 增强 支持 DirConfigObject 和 glob 模式
dts ✅ 增强 新增 DtsConfig 对象(filepath + mode)
vueTemplate ✅ 不变 保留,同时新增 vueDirectives
ignore ✅ 不变 ---
include --- ✅ 新增 文件包含过滤(替代 fileFilter
exclude --- ✅ 新增 文件排除过滤
dtsMode --- ✅ 新增 'append''overwrite'
dtsPreserveExts --- ✅ 新增 DTS 中保留文件扩展名
eslintrc --- ✅ 新增 ESLint globals 配置生成
biomelintrc --- ✅ 新增 Biome globals 配置生成
resolvers --- ✅ 新增 自定义解析器
packagePresets --- ✅ 新增 包预设
cache --- ✅ 新增 缓存配置(默认 true)
ignoreDts --- ✅ 新增 DTS 忽略列表
viteOptimizeDeps --- ✅ 新增 Vite 预优化集成(默认 false)
commentsDisable --- ✅ 新增 注释禁用标记列表
vueDirectives --- ✅ 新增 Vue 指令自动导入配置
dirsScanOptions --- ✅ 新增 目录扫描选项
defaultExportByFilename --- ✅ 新增 默认导出按文件名
injectAtPosition ✅ 不变 ---
fileFilter ❌ 移除 使用 include/exclude 替代

六、子路径导出变更

6.1 移除的导出

  • 类型:ImportMappingResolvedImport
  • 函数:migrateLegacyOptionsresolvedImportToInlineinlineToResolvedImportimportMappingToInlines

6.2 新增的导出

  • 类型:ImportInlinePresetDefinitionDirConfigDirConfigObjectDirsScanOptionsDtsConfigDtsConfigObjectInlineImportConfigEslintrcConfigBiomelintrcConfigAutoImportCacheCacheConfigVueDirectivesConfigImportMeta
  • 函数:resolveImportsConfigbuildNameLookupfindPresetexpandPresetresolvePackagePresetgenerateEslintrcgenerateBiomelintrc

七、实战场景

7.1 纯 Vite 项目(推荐配置)

typescript 复制代码
import { defineConfig } from 'vite'
import { autoImport } from '@meng-xi/vite-plugin'

export default defineConfig({
	plugins: [
		autoImport({
			imports: ['vue', 'vue-router', 'pinia'],
			dts: 'src/auto-imports.d.ts',
			vueTemplate: true,
			viteOptimizeDeps: true, // 纯 Vite 项目可安全开启
			eslintrc: { enabled: true }
		})
	]
})

7.2 uni-app 项目

typescript 复制代码
import { defineConfig } from 'vite'
import uni from '@dcloudio/vite-plugin-uni'
import { autoImport } from '@meng-xi/vite-plugin'

export default defineConfig({
	plugins: [
		uni(),
		autoImport({
			imports: ['vue'],
			dts: true,
			vueTemplate: true
			// ⚠️ uni-app 中不要开启 viteOptimizeDeps(vue 已被框架 external 化)
		})
	]
})

7.3 目录扫描 + 自定义 composables

typescript 复制代码
autoImport({
	imports: ['vue'],
	dirs: ['./src/composables/**', './src/utils'],
	dts: { filepath: 'src/auto-imports.d.ts', mode: 'append' },
	dirsScanOptions: {
		fileFilter: file => !file.includes('.test.')
	}
})

7.4 注释禁用

typescript 复制代码
// 整个文件禁用自动导入
// @unimport-disable

// 仅某一行禁用
// const x = someGlobal() // @unimport-disable

八、升级指南

8.1 从 1.0.0 升级

bash 复制代码
pnpm update @meng-xi/vite-plugin@^1.1.0

无需修改代码的情况(大多数用户):

  • 使用 imports: { vue: ['ref', 'reactive'] } Record 格式 → 仍支持
  • 使用 imports: { vue: ['*'] } 通配符 → 仍支持,推荐改为 'vue'
  • 使用 dirs: ['./composables'] → 仍支持

需要修改代码的情况

场景 修改方式
使用了 ImportMapping 类型 改为 InlineImportConfig 或预设字符串
使用了 ResolvedImport 类型 改为 ImportInline
使用了 fileFilter 选项 改为 include / exclude
直接引用了 helpers/compat 移除引用,旧格式不再支持

8.2 推荐优化

升级后推荐逐步迁移到新特性:

typescript 复制代码
// 旧:手动列举
autoImport({ imports: { vue: ['ref', 'reactive', 'computed', 'watch'] } })

// 新:使用预设(覆盖更全,后续版本自动增加新 API)
autoImport({ imports: ['vue'] })

8.3 升级后验证

bash 复制代码
# 开发模式验证
vite dev

# 检查 DTS 生成
cat src/auto-imports.d.ts

# 如启用了 ESLint 配置生成
cat .eslintrc-auto-import.json

写在最后

v1.1.0 是 1.x 系列的第一个功能增强版本,聚焦于 autoImport 插件的全面升级。

重构后的 autoImport 插件在功能完整度、配置便利性和构建性能上都有显著提升:

  • 预设系统让常用库配置从手动列举变为一行搞定,且覆盖更全
  • 多种导入形式满足 alias、type、namespace 等实际需求
  • Lint 配置生成 解决了长期困扰的 no-undef 报错问题
  • 缓存与 HMR让开发体验更流畅

后续 1.x 版本将聚焦于:更多内置预设(vueuse、axios 等)、Vue 3.5+ 新 API 支持、性能持续优化。如果你有任何建议或问题,欢迎在 GitHub Issues 反馈。

相关推荐
FogLetter1 小时前
三栏布局的七十二变:从Flex到Grid,我学会了响应式设计的"降龙十八掌"
前端·面试
答案answer1 小时前
做了几年 Three.js,我为什么决定自己开发一款3D低代码编辑器
前端·three.js
Revolution611 小时前
首屏变慢后,应该先查资源下载、脚本执行还是接口请求
前端·性能优化·前端工程化
shawn03261 小时前
《疯狂动物城 2》背后的 Hybrid BVH:迪士尼如何让复杂场景跑进交互式 GPU 光追
前端·计算机图形学
圣光SG2 小时前
web操作题练习(五)
前端
杉氧2 小时前
弹性滚动的奥秘:在 Flutter 中使用 CustomScrollView 与 Sliver 打造极致流畅列表
android·前端·flutter
jinshw2 小时前
自己实现GIS配图软件(二)
前端·后端·rust
肥胖小羊2 小时前
企业微信自建应用多环境联调与路由代理方案
服务器·前端·网络
林间码客2 小时前
全栈视角下的 Mock 指南:从后端单元测试到前端 Vue 3 联调
前端·vue.js·单元测试