核心 API
ew-auto-import-tool 提供了一系列核心 API,可以在您的项目中以编程方式使用。以下是主要的 API 函数及其用法。
configureAutoImport
主函数,用于执行自动导入配置的全过程。
函数签名
1async function configureAutoImport(
2 library: Library,
3 projectPath: string = process.cwd()
4): Promise<boolean>;
参数
library
: 要配置的组件库,类型为 Library
(字符串字面量类型)
projectPath
: 项目路径,默认为当前工作目录
返回值
Promise<boolean>
: 配置是否成功的 Promise
示例
1import { configureAutoImport } from "ew-auto-import-tool";
2
3async function setup() {
4 try {
5 const success = await configureAutoImport(
6 "element-plus",
7 "/path/to/project"
8 );
9 if (success) {
10 console.log("配置成功!");
11 } else {
12 console.log("配置失败!");
13 }
14 } catch (error) {
15 console.error("配置出错:", error);
16 }
17}
18
19setup();
实现细节
configureAutoImport
函数执行以下步骤:
- 调用
checkProject
检查项目结构
- 调用
installDependencies
安装必要的依赖
- 调用
updateViteConfig
更新 Vite 配置
- 调用
updateTsConfig
更新 TypeScript 配置(如果项目使用 TypeScript)
- 调用
generateDeclarationFiles
生成声明文件
类型定义
Library
支持的组件库类型:
1type Library = "element-plus" | "ant-design-vue" | "naive-ui" | "vant";
PackageManager
支持的包管理器类型:
1type PackageManager = "npm" | "yarn" | "pnpm";
ProjectInfo
项目信息接口:
1interface ProjectInfo {
2 isValid: boolean; // 项目是否有效
3 isVue: boolean; // 是否为Vue项目
4 isVite: boolean; // 是否使用Vite
5 hasTypeScript: boolean; // 是否使用TypeScript
6 packageManager: PackageManager; // 使用的包管理器
7 viteConfigPath?: string; // Vite配置文件路径
8 tsConfigPath?: string; // TypeScript配置文件路径
9 errors?: string[]; // 错误信息
10}
LibraryConfig
组件库配置接口:
1interface LibraryConfig {
2 dependencies: string[]; // 需要安装的依赖
3 resolverImport: string; // 解析器导入语句
4 resolverName: string; // 解析器名称
5}
导出的模块
除了主函数 configureAutoImport
外,该工具还导出了以下模块,可以单独使用:
checkProject
: 项目检查器
installDependencies
: 依赖管理器
updateViteConfig
: Vite 配置管理器
updateTsConfig
: TypeScript 配置管理器
generateDeclarationFiles
: 声明文件生成器
这些模块的详细 API 请参考各自的文档页面: