Block Specific CSS

One of the new developments in full site editing is the ability to have block specific css that only loads when the block is loaded. This allows for much lighter and more modular css.

We begin with this function:

/*
	 * Load additional block styles.
	 * See details on how to add more styles in the readme.txt.
	 */
	$styled_blocks = [ 'button', 'quote', 'navigation', 'search' ];
	foreach ( $styled_blocks as $block_name ) {
		$args = array(
			'handle' => "geoffcordner2024-$block_name",
			'src'    => get_theme_file_uri( "assets/css/blocks/$block_name.min.css" ),
			'path'   => get_theme_file_path( "assets/css/blocks/$block_name.min.css" ),
		);
		// Replace the "core" prefix if you are styling blocks from plugins.
		wp_enqueue_block_style( "core/$block_name", $args );
	}

This does the following:

  • Registers styles for specific blocks (button, quote, navigation, and search) that are listed in the array $styled_blocks.
  • It dynamically constructs the paths to the CSS files based on the block names and enqueues these styles only for the blocks specified in the $styled_blocks array.

The next thing we do is structure our css to look like this: assets/css/blocks. Inside the blocks directory will be our compiled css.

Last of all, I like to compile my css. In building this block theme boilerplate, I began with a theme containing a gulpfile.js that came from Carolina Nymark’s fullsiteediting.com and reworked it. I reworked it to use gulp modules that are not deprecated (which means we have to run node 18) and to do scss compiling, which the original did not do. My revised gulpfile.js is here:

const gulp = require('gulp'),
  clean = require('gulp-clean'),
  postcss = require('gulp-postcss'),
  rename = require('gulp-rename'),
  cssnano = require('cssnano'),
  sass = require('gulp-sass')(require('sass')),
  sourcemaps = require('gulp-sourcemaps'),
  autoprefixer = require('gulp-autoprefixer'),
  cleanCSS = require('gulp-clean-css'),
  path = require('path'),
  glob = require('glob'),
  mergeStream = require('merge-stream');

// Watch task
gulp.task('watch', function () {
  gulp.watch('css/src/**/*.scss', gulp.series('scss', 'minify-css', 'blocks', 'minify-blocks'));
});

// Clean CSS task
gulp.task('clean-css', function () {
  return gulp
    .src(['assets/css/main.css', 'assets/css/main.min.css'], {
      read: false,
      allowEmpty: true,
    })
    .pipe(clean());
});

// Clean Blocks task
gulp.task('clean-blocks', function () {
  return gulp
    .src(['assets/css/blocks/*.css', 'assets/css/blocks/*.min.css'], {
      read: false,
      allowEmpty: true,
    })
    .pipe(clean());
});

// SCSS task for main stylesheet
gulp.task('scss', function () {
  return gulp
    .src('css/src/main.scss')
    .pipe(sourcemaps.init())
    .pipe(sass().on('error', sass.logError))
    .pipe(autoprefixer())
    .pipe(sourcemaps.write('.'))
    .pipe(rename('main.css'))
    .pipe(gulp.dest('assets/css'));
});

// Minify main stylesheet task
gulp.task('minify-css', function () {
  return gulp
    .src('assets/css/main.css')
    .pipe(sourcemaps.init({ loadMaps: true }))
    .pipe(cleanCSS())
    .pipe(rename('main.min.css'))
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest('assets/css'));
});

// Compile SCSS blocks task
gulp.task('blocks', function () {
  const files = glob.sync('css/src/blocks/*.scss');
  const tasks = files.map(function (file) {
    const blockName = path.basename(file, '.scss');
    return gulp
      .src(file)
      .pipe(sourcemaps.init())
      .pipe(sass().on('error', sass.logError))
      .pipe(autoprefixer())
      .pipe(sourcemaps.write('.'))
      .pipe(rename({ basename: blockName }))
      .pipe(gulp.dest('assets/css/blocks'));
  });
  return mergeStream(...tasks);
});

// Minify SCSS blocks task
gulp.task('minify-blocks', function () {
  const files = glob.sync('assets/css/blocks/*.css');
  const tasks = files.map(function (file) {
    const blockName = path.basename(file, '.css');
    return gulp
      .src(file)
      .pipe(sourcemaps.init({ loadMaps: true }))
      .pipe(cleanCSS())
      .pipe(rename({ basename: blockName, suffix: '.min' }))
      .pipe(sourcemaps.write('.'))
      .pipe(gulp.dest('assets/css/blocks'));
  });
  return mergeStream(...tasks);
});

// Default task
gulp.task(
  'default',
  gulp.series('clean-css', 'clean-blocks', 'scss', 'minify-css', 'blocks', 'minify-blocks')
);

The last thing I need to do is create a blocks directory inside css/src/. There, in css/src/blocks I will have all my scss files. Since I began with a handful of blocks, I converted the css to scss, moved it into the css/src/blocks directory, and now my assets/css/blocks folder (where these files originally resided) will contain the files being compiled when I run $ gulp.

Leave a Reply

Your email address will not be published. Required fields are marked *