UNPKG

@unizap/unicss

Version:

Unicss: Build sleek interfaces straight from your markup. Fast, modern, utility-first CSS framework for rapid UI development.

85 lines (72 loc) 2.25 kB
const fs = require('fs'); const path = require('path'); const generateCSS = require('./dist/index.js'); /** * Vite plugin for UniCSS integration * @param {Object} options - Plugin options * @param {string} options.output - Output CSS file path (default: 'src/unicss.css') * @param {boolean} options.skipBase - Skip base CSS styles (default: false) * @returns {import('vite').Plugin} */ function unicssPlugin(options = {}) { const { output = 'src/unicss.css', skipBase = false } = options; let isWatching = false; const outputPath = path.resolve(process.cwd(), output); function generateAndWrite() { try { const css = generateCSS({ skipBase }); const outDir = path.dirname(outputPath); if (!fs.existsSync(outDir)) { fs.mkdirSync(outDir, { recursive: true }); } fs.writeFileSync(outputPath, css); console.log(`UniCSS generated at ${output}`); return true; } catch (error) { console.error(`UniCSS generation failed: ${error.message}`); return false; } } return { name: 'vite-plugin-unicss', configResolved(resolvedConfig) { // Determine if we're in dev mode (watch mode) isWatching = resolvedConfig.command === 'serve'; }, buildStart() { // Generate CSS on build start if (!generateAndWrite()) { this.error('UniCSS generation failed'); } // Add output file to watch list if (fs.existsSync(outputPath)) { this.addWatchFile(outputPath); } }, handleHotUpdate({ file, server }) { // Regenerate CSS when watched files change, but never react to our own output if (isWatching && file !== outputPath && ( file.endsWith('.html') || file.endsWith('.js') || file.endsWith('.jsx') || file.endsWith('.ts') || file.endsWith('.tsx') || file.endsWith('.vue') || file.endsWith('.svelte') || file.endsWith('.css') )) { console.log('File changed, regenerating UniCSS...'); generateAndWrite(); // Trigger HMR for the CSS file server.ws.send({ type: 'full-reload', path: '*' }); } } }; } module.exports = unicssPlugin;