Skip to content

Instantly share code, notes, and snippets.

@andreilupu
Created December 17, 2023 12:30
Show Gist options
  • Save andreilupu/d100753cea166bd1f53f47a4165076fb to your computer and use it in GitHub Desktop.
Save andreilupu/d100753cea166bd1f53f47a4165076fb to your computer and use it in GitHub Desktop.
A simple PoC inspired by Gutenberg's build process of compiling SCSS files in packages/blocks. I'm just exploring a way of build/watch SCSS files in a blocks library. https://github.com/WordPress/gutenberg/blob/cdeca67b63635cca295ba8f4874130c53f394ab0/bin/packages/build-worker.js#L83
/**
* External dependencies
*/
const { promisify } = require( 'util' );
const path = require( 'path' );
const makeDir = require( 'make-dir' );
const fs = require("fs");
const sass = require( 'sass' );
const postcss = require( 'postcss' );
/**
* Promisified sass.render.
*
* @type {Function}
*/
const renderSass = promisify( sass.render );
/**
* Promisified fs.readFile.
*
* @type {Function}
*/
const readFile = promisify( fs.readFile );
/**
* Promisified fs.writeFile.
*
* @type {Function}
*/
const writeFile = promisify( fs.writeFile );
async function buildCSS( file ) {
const srcFile = path.resolve(file + '.scss');
const outputFile = path.resolve(file + '.css');
const [ , contents ] = await Promise.all( [
makeDir( path.dirname( srcFile ) ),
readFile( srcFile, 'utf8' ),
] );
const builtSass = await renderSass( {
file,
data: ''.concat( '@use "sass:math";', contents ),
} );
const result = await postcss(
require( '@wordpress/postcss-plugins-preset' )
).process( builtSass.css, {
from: 'src/app.css',
to: 'dest/app.css',
} );
await Promise.all( [
writeFile( outputFile, result.css ),
// writeFile( outputFileRTL, resultRTL.css ), // we could also auto rtls
] );
}
// plain simple example on how to call this on a specific file.
// it will compile style.scss into style.css
buildCSS('./src/assets/blocks/myblock/style');
{
"scripts" => {
"build-style": "node ./worker.js"
},
"devDependencies": {
"@wordpress/postcss-plugins-preset": "^4.32.0",
"postcss": "^8.4.32",
"sass": "^1.69.5",
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment