🛠️ Unindex:推荐一款自动化索引文件生成工具
2025年4月17日 11:19
📖 开发背景
作为一名前端开发者,在维护组件库和工具函数目录时,总会遇到下面的困扰:
- 每次新增组件/工具文件时,都需要手动更新
index.*
文件做引入或重新导出 - 基于构建工具的
import.meta.glob
的导入在 Re-Export 时会丢失对应的类型 - 不同的语言文件对索引文件的引入方式不同,但内容大体上仍然属于重复性工作
查找了 npm 暂时没有发现一个能同时满足以下需求的工具:
- 支持可视化配置
- 可定制生成规则
- 支持监听模式
- 可脱离构建工具直接运行
"既然找不到合适的轮子,那就自己造一个!" -- 于是 unindex 诞生了!
✨ unindex 的核心特点
1. 极简配置,开箱即用
// 最简单的配置
export default defineConfig({
// 定义入口目录
entryDir: 'src/hooks'
})
只需指定目录,unindex 就会自动生成规范的导出文件,未配置 outFile
时将尝试从匹配的文件列表中进行获取扩展名。
2. 深度定制能力
export default defineConfig({
entryDir: 'src/hooks',
glob: {
patterns: '**/*.ts',
},
// 更改生成的代码片段
codeGenerator: ({ file, relativePath }) => {
return `export { default as use${pascalCase(file.slice(file.lastIndexOf('/') + 1).replace(/\.tsx?$/, ''))} } from './${relativePath}';`
},
// 更改输出内容
contentGenerator: ({ codes }) => {
return `\
/* Generated by unindex */
${codes.join('\n')}
`
}
})
3. 多场景支持
- 组件库开发:自动导出所有组件
- 工具函数集:统一管理工具方法
- 文档系统:自动生成目录索引
- 样式管理:自动导入 CSS/SCSS 文件
// 支持配置项数组
export default defineConfig([
{
entryDir: 'src/hooks',
glob: {
// 需要匹配的文件
patterns: '**/*.ts',
// 忽略以 `_` 开头的文件和目录
// ignore: '**/_*',
// 仅忽略以 `_` 开头的文件
ignore: '**/_.*',
},
},
{
entryDir: 'src/styles',
glob: {
patterns: '**/*.css',
},
// 更改生成的代码片段
codeGenerator: ({ relativePath }) => `@import './${relativePath}';`,
},
{
entryDir: 'docs/pages',
// 更改输出的文件名
outFile: 'Home.md',
glob: {
patterns: '**/*.md',
},
codeGenerator: ({ file, relativePath }) => `[${file}](./${relativePath})`,
// 更改输出的内容
contentGenerator: ({ codes }) => {
return `\
# 目录
${codes.map((code) => `- ${code}`).join('\n')}
`
},
},
])
4. 支持监听模式
export default defineConfig({
// 定义入口目录
entryDir: 'src/hooks',
+ watch: true, // 优先级大于命令行 `--watch` 参数
})
npx unindex --watch
文件新增、删除、重命名时自动重新生成。
🚀 快速入门
- 安装:
# npm
npm i -D unindex
# yarn
yarn add -D unindex
# pnpm
pnpm add -D unindex
- 创建配置文件
unindex.config.[js,ts,mjs,cjs,mts,cts,json]
:
import { defineConfig } from 'unindex'
export default defineConfig({
entryDir: 'src/hooks',
glob: {
patterns: '**/*.{ts,tsx}',
ignore: '**/*.spec.*'
}
})
- 运行:
# 命令行
npx unindex
# 或添加到 package.json
{
"scripts": {
"unindex": "unindex"
}
}
结语
你的项目是否也在为导出文件烦恼?试试 unindex,让工具代替重复劳动!
项目已开源,欢迎 Star 和贡献代码!
项目地址: github.com/l246804/uni…