gist-weborigami-postcss/transform-postcss.js

59 lines
1.8 KiB
JavaScript

import postcss from 'postcss';
import postcssInlineImport from 'postcss-import';
import postcssMinify from 'postcss-minify';
import {readFile} from 'node:fs/promises';
//STEP 1: read the input CSS file. Hardcoded for this project.
//This file could be modified to export a function taking the filepath as an argument.
const input = await readFile('src/css/style.css');
let result;
//STEP 2: process the CSS
try {
result = await postcss(
//plugins
[
postcssInlineImport, //for inlining imports, e.g. normalize.css
postcssMinify
])
.process(input,{
from: 'src/css/style.css',
to: '/css/style.css',
map: true, //inlines the sourcemap in output css. exports.default.map will be undefined.
//Could also use `map: {inline: false}` to output it to exports.default.map.
})
.then(result => {
//handle warnings produced by plugins
result.warnings().forEach(warn => {
process.stderr.write(warn.toString());
});
return result;
})
} catch (error) {
//Handle CSS Syntax Errors: don't show JS stack trace.
if (error.name === 'CssSyntaxError') {
process.stderr.write(error.message + error.showSourceCode() + '\n')
} else {
throw error;
}
}
//STEP 3: extract the results we want
//Only want css and map from `results` object (note: potentially more interesting stuff in there)
//We're going to transform these to output paths in `site.ori`.
//If `result` is undefined, output an error message as a string.
//This is one way to supress undefined access errors in the following code, while also doing something useful.
const { css, map } = result || {
css: 'there was an error in the CSS processing pipeline. Check the logs.',
map: undefined
};
//STEP 4: export an object which Origami can traverse
export default {
css,
map
}