mirror of
https://github.com/captbaritone/webamp.git
synced 2026-01-23 10:15:31 +00:00
Minify css using postcss (#732)
* Minify css using postcss * Optimize data uris as build time
This commit is contained in:
parent
b563eebf96
commit
2bcd69762d
8 changed files with 1882 additions and 46 deletions
37
scripts/postcss-optimize-data-uri-pngs.js
Normal file
37
scripts/postcss-optimize-data-uri-pngs.js
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
const postcss = require("postcss");
|
||||
const dataUriToBuffer = require("data-uri-to-buffer");
|
||||
const imagemin = require("imagemin");
|
||||
const imageminOptipng = require("imagemin-optipng");
|
||||
|
||||
const DATA_URL_REGEX = new RegExp(/url\((data:image\/png;base64,.+)\)/gi);
|
||||
const DATA_URL_PROPS_REGEX = /^(background(?:-image)?)|(content)|(cursor)/;
|
||||
|
||||
async function optimizeDataUri(dataUri) {
|
||||
const buffer = dataUriToBuffer(dataUri);
|
||||
const optimized = await imagemin.buffer(buffer, {
|
||||
use: [imageminOptipng()]
|
||||
});
|
||||
return `data:image/png;base64,${optimized.toString("base64")}`;
|
||||
}
|
||||
|
||||
module.exports = postcss.plugin("postcss-optimize-data-uri-pngs", () => {
|
||||
return async function(css) {
|
||||
// walkDecls does not let us work async, so we collect the async work we
|
||||
// need to do here, and await it at the end
|
||||
const promisesFactories = [];
|
||||
css.walkDecls(DATA_URL_PROPS_REGEX, decl => {
|
||||
let matches;
|
||||
// WTF JavaScript. This is the worst API for iterating RegEx matches.
|
||||
while ((matches = DATA_URL_REGEX.exec(decl.value))) {
|
||||
const [, dataUri] = matches;
|
||||
promisesFactories.push(async () => {
|
||||
decl.value = decl.value.replace(
|
||||
dataUri,
|
||||
await optimizeDataUri(dataUri)
|
||||
);
|
||||
});
|
||||
}
|
||||
});
|
||||
await Promise.all(promisesFactories.map(p => p()));
|
||||
};
|
||||
});
|
||||
10
scripts/postcss-optimize-data-uri-pngs.test.js
Normal file
10
scripts/postcss-optimize-data-uri-pngs.test.js
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
const fs = require("fs");
|
||||
const postcss = require("postcss");
|
||||
|
||||
const plugin = require("./postcss-optimize-data-uri-pngs");
|
||||
|
||||
const css = fs.readFileSync("./css/base-skin.css", "utf8");
|
||||
it("does something", async () => {
|
||||
const result = await postcss([plugin({})]).process(css);
|
||||
expect(result.css.length).toBeLessThan(css.length);
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue