pixelplanet/scripts/minifyCss.js

59 lines
2.0 KiB
JavaScript
Raw Normal View History

/*
2021-01-29 21:46:58 +00:00
* Minify CSS
* currently just css files for themes are loades seperately,
* so files beginning with "theme-" in the src/styles folder will
* be read and automatically added.
*
* @flow
*/
2021-01-29 21:46:58 +00:00
/* eslint-disable import/no-extraneous-dependencies */
/* eslint-disable no-console */
import fs from 'fs';
import path from 'path';
import CleanCSS from 'clean-css';
import crypto from 'crypto';
2021-01-29 01:15:33 +00:00
const assetdir = path.resolve(__dirname, '..', 'build', 'public', 'assets');
const builddir = path.resolve(__dirname, '..', 'build');
2021-01-29 01:15:33 +00:00
const FOLDER = path.resolve(__dirname, '..', 'src', 'styles');
2021-01-29 21:46:58 +00:00
const FILES = fs.readdirSync(FOLDER).filter((e) => e.startsWith('theme-'));
FILES.push('default.css');
async function minifyCss() {
console.log('Minifying css');
const assets = {};
FILES.forEach((file) => {
const input = fs.readFileSync(path.resolve(FOLDER, file), 'utf8');
const options = {};
const output = new CleanCSS(options).minify(input);
if (output.warnings && output.warnings.length > 0) {
for (let i = 0; i < output.warnings.length; i += 1) {
console.log('\x1b[33m%s\x1b[0m', output.warnings[i]);
}
}
if (output.errors && output.errors.length > 0) {
for (let i = 0; i < output.errors.length; i += 1) {
console.log('\x1b[31m%s\x1b[0m', output.errors[i]);
}
2021-01-29 21:46:58 +00:00
throw new Error('Minify CSS Error Occured');
}
// eslint-disable-next-line max-len
console.log('\x1b[33m%s\x1b[0m', `Minified ${file} by ${Math.round(output.stats.efficiency * 100)}%`);
const hash = crypto.createHash('md5').update(output.styles).digest('hex');
2021-01-29 21:46:58 +00:00
let key = file.substr(0, file.indexOf('.'));
if (key.startsWith('theme-')) {
key = key.substr(6);
}
const filename = `${key}.${hash.substr(0, 8)}.css`;
2021-01-29 21:46:58 +00:00
fs.writeFileSync(path.resolve(assetdir, filename), output.styles, 'utf8');
assets[key] = `/assets/${filename}`;
});
const json = JSON.stringify(assets);
2021-01-29 21:46:58 +00:00
fs.writeFileSync(path.resolve(builddir, 'styleassets.json'), json);
}
export default minifyCss;