Vite Config Manager

The Vite Config Manager module is responsible for updating the Vite configuration file to include the auto-import plugins. It provides functions to locate, parse, and modify the Vite configuration file to enable automatic component and API imports.

API Reference

updateViteConfig

Signature:

1function updateViteConfig(
2  options: UpdateViteConfigOptions
3): Promise<UpdateViteConfigResult>;

Parameters:

  • options: UpdateViteConfigOptions - Configuration options for Vite config update
    • path?: string - The path to the project directory (defaults to current directory)
    • library: string - The component library to configure
    • viteConfigPath?: string - The path to the Vite configuration file (auto-detected if not specified)

Returns:

  • Promise<UpdateViteConfigResult> - A promise that resolves to the update result
    • success: boolean - Whether the update was successful
    • viteConfigPath: string - The path to the updated Vite configuration file
    • configUpdated: boolean - Whether the configuration was actually modified

Example:

1import { updateViteConfig } from "ew-auto-import-tool";
2
3async function configureVite() {
4  try {
5    const result = await updateViteConfig({
6      path: "./my-vue-project",
7      library: "element-plus",
8    });
9
10    if (result.success) {
11      console.log(
12        `Successfully updated Vite config at ${result.viteConfigPath}`
13      );
14      if (result.configUpdated) {
15        console.log(
16          "Configuration was modified to include auto-import plugins"
17        );
18      } else {
19        console.log("Configuration already included auto-import plugins");
20      }
21    } else {
22      console.error("Failed to update Vite configuration");
23    }
24  } catch (error) {
25    console.error("Error updating Vite configuration:", error);
26  }
27}
28
29configureVite();

Implementation Details

The Vite Config Manager performs the following operations:

  1. Configuration File Detection

    • Locates the Vite configuration file (vite.config.js/ts)
    • Supports both JavaScript and TypeScript configuration files
  2. AST Parsing and Transformation

    • Parses the configuration file into an Abstract Syntax Tree (AST)
    • Analyzes the existing configuration to avoid duplicate plugins
    • Adds the necessary import statements for auto-import plugins
    • Adds plugin configurations with appropriate resolvers
  3. Code Generation

    • Transforms the modified AST back to code
    • Preserves formatting and comments as much as possible
    • Writes the updated configuration back to the file

Library-Specific Configurations

The module adds different resolver configurations based on the selected component library:

Element Plus

1import AutoImport from "unplugin-auto-import/vite";
2import Components from "unplugin-vue-components/vite";
3import { ElementPlusResolver } from "unplugin-vue-components/resolvers";
4
5export default defineConfig({
6  plugins: [
7    // ... existing plugins
8    AutoImport({
9      resolvers: [ElementPlusResolver()],
10    }),
11    Components({
12      resolvers: [ElementPlusResolver()],
13    }),
14  ],
15});

Ant Design Vue

1import AutoImport from "unplugin-auto-import/vite";
2import Components from "unplugin-vue-components/vite";
3import { AntDesignVueResolver } from "unplugin-vue-components/resolvers";
4
5export default defineConfig({
6  plugins: [
7    // ... existing plugins
8    AutoImport({
9      resolvers: [AntDesignVueResolver()],
10    }),
11    Components({
12      resolvers: [AntDesignVueResolver()],
13    }),
14  ],
15});

Source Code Analysis

The Vite Config Manager uses AST manipulation libraries to modify the configuration file. It follows these steps:

  1. Read the Vite configuration file
  2. Parse it into an AST using a parser like Babel or TypeScript
  3. Traverse the AST to find the plugins array
  4. Check if auto-import plugins are already configured
  5. Add the necessary import statements and plugin configurations
  6. Generate code from the modified AST
  7. Write the updated code back to the file
1// Simplified implementation
2async function updateViteConfig(
3  options: UpdateViteConfigOptions
4): Promise<UpdateViteConfigResult> {
5  const projectPath = options.path || process.cwd();
6  const viteConfigPath =
7    options.viteConfigPath || (await findViteConfig(projectPath));
8
9  if (!viteConfigPath) {
10    throw new Error("Vite configuration file not found");
11  }
12
13  // Read the configuration file
14  const configContent = fs.readFileSync(viteConfigPath, "utf-8");
15
16  // Parse the file into an AST
17  const ast = parseToAST(configContent, viteConfigPath);
18
19  // Check if plugins are already configured
20  const hasAutoImportPlugin = checkForPlugin(ast, "AutoImport");
21  const hasComponentsPlugin = checkForPlugin(ast, "Components");
22
23  if (hasAutoImportPlugin && hasComponentsPlugin) {
24    return {
25      success: true,
26      viteConfigPath,
27      configUpdated: false,
28    };
29  }
30
31  // Add import statements
32  addImportStatement(ast, "unplugin-auto-import/vite", "AutoImport");
33  addImportStatement(ast, "unplugin-vue-components/vite", "Components");
34
35  // Add resolver import based on library
36  const resolverName = getResolverName(options.library);
37  addImportStatement(
38    ast,
39    "unplugin-vue-components/resolvers",
40    resolverName,
41    true
42  );
43
44  // Add plugin configurations
45  addPluginConfigurations(ast, resolverName, options.library);
46
47  // Generate code from the modified AST
48  const updatedContent = generateCode(ast);
49
50  // Write the updated code back to the file
51  fs.writeFileSync(viteConfigPath, updatedContent, "utf-8");
52
53  return {
54    success: true,
55    viteConfigPath,
56    configUpdated: true,
57  };
58}
59
60function getResolverName(library: string): string {
61  switch (library) {
62    case "element-plus":
63      return "ElementPlusResolver";
64    case "ant-design-vue":
65      return "AntDesignVueResolver";
66    case "naive-ui":
67      return "NaiveUiResolver";
68    case "vant":
69      return "VantResolver";
70    default:
71      throw new Error(`Unsupported library: ${library}`);
72  }
73}

Error Handling

The Vite Config Manager includes robust error handling to provide clear feedback when issues are encountered:

  • Configuration file not found errors
  • Parsing errors for malformed configuration files
  • AST traversal and manipulation errors
  • File writing errors

These errors are propagated to the caller with descriptive messages to help users troubleshoot issues.