UNPKG

nur

Version:
122 lines (95 loc) 3.82 kB
#!/usr/bin/env node const fs = require('fs'); const cheerio = require('cheerio'); const program = require('commander'); // const colors = require('colors'); // for colored output const log = console.log; const tags = require('./tags'); const version = '1.0.0-rc1'; program .version(version, '-v, --version') .option('-e, --entry [file]', 'Input HTML file') .option('-o, --output [folder]', 'Output folder to save generated HTML & CSS style'); // .option('--minify-css', 'Minify CSS output') // .option('--minify-html', 'Minify HTML output'); program.on('--help', function () { log(''); log('Examples:'); log(' $ nur --entry index.html --ouput ./dist'); log(' $ nur -e index.html -o dist'); }); program.parse(process.argv); log(''); // line break if (program.entry && program.output) { log(`>nur@${version} build ${program.entry}`); if (!fs.existsSync('./build')) { fs.mkdir('./build', (err) => { if (err) throw err; }); } else { return; } fs.exists(program.entry, function (exists) { if (!exists) throw 'File does not exists.' }); fs.readFile(program.entry, 'utf-8', (err, data) => { if (err) throw err; const $ = cheerio.load(data); const classAssembly = []; $('*') .each((_, el) => { const classesNames = []; const classContent = $(el).attr('class'); if (classContent) { const separateClasses = classContent.split(' '); separateClasses.forEach(el => { const properties = []; const separateUnderscore = el.split('='); if (!separateUnderscore[1]) return; classesNames.push(separateUnderscore[0]); const separatePlus = separateUnderscore[1].split("+").join(" "); const separateSemicolon = separatePlus.split(';'); separateSemicolon.forEach(el => { const separateColon = el.split(':'); if (!tags[separateColon[0]]) return; properties.push({ property: tags[separateColon[0]], value: separateColon[1] }) }); if (!properties.length) return; classAssembly.push({ class: separateUnderscore[0], rules: properties }) }) } // the code below is used to rewrite the DOM with classes without property if (classesNames.length) { $(el).removeClass($(el).attr('class')) } for (className of classesNames) { $(el).addClass(className) } }); const classGeneration = classAssembly.map(el => ( `.${el.class} { ${el.rules.map(({ property, value }) => `${property}: ${value};`).join('\n ')} }` )).join('\n\n') // TODO: check if output exists and is a directory fs.writeFile(program.output + '/style.css', classGeneration, {flag: "w"}, (err) => { if (err) throw err; else log('\nStylesheet created.'); }); fs.writeFile(program.output + '/index.html', $.html(), {flag: "w"}, (err) => { // TODO: use the same file name as entry if (err) throw err; else { log('HTML file created.'); log('\nJob finished!'); } }); }); } else { program.outputHelp(); }