unplugin-export-collector 开箱即用地让你的小库库支持unplugin-auto-import吧!

35 阅读2分钟

开箱即用地让你的小库库支持unplugin-auto-import吧!

项目开源在 github,更多细节请移步仓库。

另外还请点下小星星喵~ 点下小星星谢谢喵~~

简介

unplugin-export-collector 可以递归地获取一个文件所有具名导出的名称。

举个例子,有文件index.tsfunc.ts

// index.ts
export const one = 1
export * from './func.ts' // 从其他文件导出。
export * from 'vue' // 重导出将会被忽略。


// func.ts
export function func(){}

通过对上面的 index.ts 使用unplugin-export-collector,你可以获取这样一个数组:

import { expCollector } from 'unplugin-export-collector/core'

const val = await expCollector('./src/index.ts')
console.log(val) // 结果是 ['one', 'func']

unplugin-export-collector 是我创作的一个新库库,底层基于 @swc 将代码转化为抽象语法树,通过对AST的分析递归地实现文件导出的获取。

安装

$ pnpm i -D unplugin-export-collector

使用

在上面的例子中,我们使用expCollector方法获取文件的具名导出,事实上这只是方便扩展而暴露的底层方法。如果你仅仅是想要让自己的库开箱即用的提供unplugin-auto-import支持,你可以像这样更加简单方便的使用:

// vite.config.js
import ExportCollector from 'unplugin-export-collector/vite'

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

不仅仅是Vite,这个插件支持绝大多数主流打包器,包括RollupWebpackesbuild,关于其他打包工具的更多细节请移步github仓库的readme~

ExportCollector 会默认对你的./src/index进行处理,你也可以通过entries选项手动设置入口文件,更多选项请移步github仓库的readme下方~

还是以上面的例子进行举例,那么结果打包后将会是:

// index.ts
export const one = 1
export * from './func.ts' // 从其他文件导出。
export * from 'vue' // 重导出将会被忽略。

// --- Auto-Generated By Unplugin-Export-Collector ---

const __UnExportList = ['one', 'func'] as const

export function autoImport(map?: Partial<{ [K in typeof __UnExportList[number]]: string }>): Record<string, (string | [string, string])[]> {
  return {
    'unplugin-export-collector': __UnExportList.map(v => map && map[v] ? [v, map[v]] as [string, string] : v),
  }
}

// --- Auto-Generated By Unplugin-Export-Collector ---

unplugin-export-collector会自动生成一段代码,以提供开箱即用的支持,并附带完全的类型支持。

他会自动识别你的项目是ts还是js,如果是js,他会通过jsdoc以实现类型支持。

尾声

我的github主页:github.com/s3xysteak 。内有大量垃圾包,欢迎交流与贡献!

我的库 :

  • vite-plugin-cesium-build cesium的Vite插件,一键完成各种准备工作。
  • cesium-use 非侵入式的基于vue的轻量cesium库,有配套文档网站。
  • tauri-version tauri的版本升级ci,提供类似于npm version的行为。

技术交流请加 : (并没有那样的群!)

更多其他文章见 : (并没有那样的其他文章!)