Monday 23 May 2016

Minify custom SharePoint themable CSS with Gulp

The ability to create your own themable CSS has been present in SharePoint for a long time:

How to: Make custom CSS files themable in SharePoint 2013

Working with the SharePoint Theming Engine

You can even define custom names/properties in your .spcolor files which can be used in your custom CSS. My colleague Matt Holden has a great post on this here:

Custom .spcolor files for SharePoint Composed Looks

We were using this method in one of our SharePoint Online projects along with Gulp tasks to bundle and minify all our JavaScript/CSS files as per my previous post Simple bundle, minify and upload JS to SharePoint using Gulp

Now, the SharePoint theming engine uses CSS comments to determine the color replacement:

As per Matt's post, the theming engine replaces the values at run-time to the color defined in the ContentAccess1 section in the spcolor file.

For the theming engine to successfully carry out this replacement, the ReplaceColor comment needs to be present in the CSS file we load in SharePoint.

When I minified the Themable.css file using the clean-css gulp plugin, it stripped out all the comments which made the replacement not work:

Then I noticed that the clean-css plugin provides an option to keepSpecialComments when it does the minification. I tired using that but it still did not work as special comments have to start with an exclamation mark: https://github.com/jakubpawlowicz/clean-css#how-to-preserve-a-comment-block

Adding an exclamation mark before the comment was not going to work as that would be invalid syntax for the SharePoint theming engine.

So my final solution was to convert the ReplaceColor comment to a special comment before processing it through the minifier, then letting the minifier do it's thing by minifying the css file but preserving the special comments, and then after the minification, again converting the special comment to a regular comment suitable for the SharePoint theming engine:

Which then gave me the minified CSS along with the required comments preserved:

Thanks for reading!

No comments: