Skip to content

配置文件读取

背景

当我们开发一个工具包的时候,如何像vite、webpack一样读取配置文件支持 .js.mjstsjosn等配置文件,比如tsup的配置

image-20241009225447581

实现

cosmiconfig

使用 cosmiconfig 实现多格式配置读取

cosmiconfig 是一个强大的库,专门用于支持加载各种格式的配置文件,包括 .js.ts.json 等。你可以用它来搜索并加载用户定义的配置文件。

  1. 安装 cosmiconfig
bash
npm install cosmiconfig
  1. 接下来,你可以这样使用它:
tsx
import { cosmiconfig } from 'cosmiconfig';

// 定义你的模块名,这将用于搜索配置文件
const explorer = cosmiconfig('你的模块名');

async function loadConfig() {
  try {
    const result = await explorer.search();
    if (result && result.config) {
      console.log('配置文件内容:', result.config);
    } else {
      console.log('未找到配置文件');
    }
  } catch (error) {
    console.error('加载配置文件时出错:', error);
  }
}

loadConfig();

支持 .ts 文件和 defineConfig({})

要支持从 TypeScript 文件加载配置,并解析其中的 defineConfig({}),可以通过 ts-node 来运行 TypeScript 文件。

安装 ts-node
bash
npm install ts-node typescript
定义 defineConfig 函数

你需要创建一个 defineConfig 函数,供 .ts 文件中的配置导出使用。

ts
// defineConfig.ts
export interface DefineConfigOptions {
}

export interface OptionCallback {
    (): Promise<DefineConfigOptions> | DefineConfigOptions
}

// defineConfig 允许接受 对象/函数 参数,返回一个对象
export const defineConfig = async (options: DefineConfigOptions | OptionCallback) => {
    return options;
}
使用 ts-node 处理 .ts 配置文件

在加载配置时,通过 ts-node 让 TypeScript 文件能够被正确解析和执行。

js
import { cosmiconfig } from 'cosmiconfig';
import { register } from 'ts-node';
import { defineConfig } from './defineConfig';

// 注册 ts-node 支持 .ts 文件
register();

// 定义配置文件的搜索路径
const explorer = cosmiconfig('yourModuleName', {
  searchPlaces: [
    'package.json',
    '.yourModuleNamerc',
    '.yourModuleNamerc.json',
    'tsup.config.js',
    'tsup.config.ts',
  ],
});

async function loadConfig() {
  try {
    const result = await explorer.search();
    if (result && result.config) {
      const config = typeof result.config === 'function'
        ? await result.config()
        : result.config;
      console.log('Loaded config:', config);
    } else {
      console.log('No config found');
    }
  } catch (error) {
    console.error('Error loading config:', error);
  }
}

loadConfig();
在 TypeScript 配置文件中使用 defineConfig
ts
// tsup.config.ts
import { defineConfig } from 'yourModuleName';

export default defineConfig({
  entry: ['src/index.ts'],
  format: ['cjs', 'esm'],
});

总结

  • 使用 cosmiconfig 来加载 .js.json.ts 等多种格式的配置文件。
  • 通过 ts-node 支持 TypeScript 配置文件。
  • 提供一个 defineConfig 函数,帮助用户在配置文件中使用更直观的语法。

这样,你的 npm 包就可以像 tsup 一样灵活地加载和解析配置文件。

前端知识体系 · wcrane