@moontra/moonui-cli
Version:
CLI tool for MoonUI component library
83 lines (67 loc) • 2.8 kB
JavaScript
const fs = require('fs');
const path = require('path');
const { generateThemeCSS } = require('../utils/theme-generator');
/**
* PostCSS plugin for MoonUI theme injection
* Automatically generates and injects theme CSS based on moonui.config.js
*/
module.exports = (options = {}) => {
return {
postcssPlugin: 'moonui-theme',
Once(root, { result }) {
try {
// Get the project root directory
const projectRoot = options.projectRoot || process.cwd();
// Path to moonui.config.js
const configPath = path.join(projectRoot, 'moonui.config.js');
// Check if config exists
if (!fs.existsSync(configPath)) {
console.warn('[MoonUI PostCSS] moonui.config.js not found. Skipping theme generation.');
return;
}
// Clear module cache to get fresh config
delete require.cache[configPath];
// Load the config
const config = require(configPath);
// Check if theme is configured
if (!config.theme) {
console.warn('[MoonUI PostCSS] No theme configuration found in moonui.config.js');
return;
}
// Check if automatic CSS generation is enabled
if (config.build?.generateThemeCSS === false) {
return;
}
// Generate theme CSS
const themeCSS = generateThemeCSS(config.theme);
// Parse the generated CSS and inject it
const processor = require('postcss');
const parsedCSS = processor.parse(themeCSS);
// Note: We no longer inject @layer base styles since themes are now scoped
// Users can opt-in to global styles by adding .moonui-theme to their root element
// Add theme variables (scoped to .moonui-theme)
const themeRules = [];
parsedCSS.each((node) => {
if (node.type === 'rule' && (node.selector === '.moonui-theme' || node.selector === '.moonui-theme.dark' || node.selector === '.dark .moonui-theme')) {
themeRules.push(node.clone());
}
});
// Insert theme rules at the beginning
themeRules.reverse().forEach(rule => {
root.prepend(rule);
});
// Add comment to indicate this was generated
root.prepend(processor.comment({
text: ' MoonUI Theme CSS - Auto-generated from moonui.config.js '
}));
// Log success
if (options.verbose !== false) {
console.log('[MoonUI PostCSS] Theme CSS injected successfully');
}
} catch (error) {
console.error('[MoonUI PostCSS] Error generating theme CSS:', error);
}
}
};
};
module.exports.postcss = true;