You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于ESM模块合并CSS框架默认与用户配置文件的问题

解决CSS框架配置合并与导出问题

核心问题拆解

  • ES模块静态import无法基于process.cwd()动态导入文件,这是路径导入失败的核心原因
  • 异步函数返回的Promise无法直接通过export default导出给同步运行的类生成函数使用

可行解决方案

方案1:同步加载用户配置(Node.js环境适配)

利用Node.js的fs和require实现同步读取,避开ES模块静态导入的限制:

import colors from './colors.config.js';
import { merge } from '../util/merge.js';
import path from 'path';
import fs from 'fs';

const defaultConfig = {
    reset: false,
    theme: {
        screens: {
            sm: '(min-width: 640px)',
            md: '(min-width: 768px)',
            lg: '(min-width: 1024px)',
            xl: '(min-width: 1280px)',
            xxl: '(min-width: 1536px)',
        },
        colors: {
            ...colors,
        },
    },
};

// 定位用户根目录的配置文件
const userConfigPath = path.resolve(process.cwd(), 'storboat.config.js');
let userConfig = {};

// 检查配置文件是否存在,存在则同步加载
if (fs.existsSync(userConfigPath)) {
    userConfig = require(userConfigPath).default || require(userConfigPath);
    // 若需支持配置热更新,可添加:delete require.cache[userConfigPath]
}

const config = merge(defaultConfig, userConfig);

export default config;

方案2:提供异步初始化函数

让用户主动调用异步方法获取配置,适配类生成函数的异步场景:

// config.js
import colors from './colors.config.js';
import { merge } from '../util/merge.js';
import path from 'path';
import fs from 'fs/promises';

const defaultConfig = {
    reset: false,
    theme: {
        screens: {
            sm: '(min-width: 640px)',
            md: '(min-width: 768px)',
            lg: '(min-width: 1024px)',
            xl: '(min-width: 1280px)',
            xxl: '(min-width: 1536px)',
        },
        colors: {
            ...colors,
        },
    },
};

export async function getConfig() {
    let userConfig = {};
    const userConfigPath = path.resolve(process.cwd(), 'storboat.config.js');
    try {
        await fs.access(userConfigPath);
        const userConfigModule = await import(userConfigPath);
        userConfig = userConfigModule.default || userConfigModule;
    } catch (err) {
        // 用户配置不存在时自动兜底
    }
    return merge(defaultConfig, userConfig);
}

用户侧使用示例:

import { getConfig } from 'storboatcss';
import { ClassGenerator } from 'storboatcss';

async function initFramework() {
    const config = await getConfig();
    const generator = new ClassGenerator(config);
    // 执行框架初始化逻辑
}

initFramework();

方案3:构建阶段注入配置(前端编译场景)

如果框架面向前端项目,可开发Webpack/Vite插件,在构建阶段解析用户配置并与默认配置合并,最终将合并后的配置静态注入到框架代码中,运行时直接使用。

关键注意事项

  • 必须处理用户配置不存在的情况,确保默认配置兜底
  • 配置合并需用深度合并逻辑,避免用户配置浅覆盖默认嵌套属性
  • 兼容用户配置的两种导出格式:export default 和 module.exports

内容的提问来源于stack exchange,提问作者bodafoo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 21:52:50