Serving SASS files for WordPress theme on IIS

I love SASS. More and more WordPress themes are supporting it. And what’s not to love? Well… it can’t be served directly like CSS. It needs to be pre-compiled before it is served.

Fortunately, there is a PHP SASS compiler that can be used to make PHP compile and serve SASS. I’m using an IIS installation, so I’ll be explaining how it can be done on a Windows machine.

First, download the latest version of scssphp (the .tar.gz can be unzipped with WinRar). Next extract the scss.inc.php from the zip and put it into the root of your application: this is the actual compiler. Create a new file called scss.php in the root and add the following script to it:

<?php

//get request URI
$requestUri = $_SERVER['REQUEST_URI'];
$lastSlash = strrpos($requestUri,'/');

//Extract directory
$dir = substr($requestUri, 0, $lastSlash);
$dir = $_SERVER['DOCUMENT_ROOT'] . str_replace('/', '\\', $dir) . '\\';

//Set 'p' file 
$_GET['p'] = substr($requestUri, $lastSlash + 1);

require "scss.inc.php";

//Process file
scss_server::serveFrom($dir);

?>

Now we need to tell IIS to serve the .scss files through our script. This can be done by adding a rewrite rule to the web.config. Most WordPress installations will have pretty urls enabled so a web.config is already present. If it is not, you must create it manually.

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>
    <rewrite>
      <rules>
        <rule name="scss" patternSyntax="Wildcard">
          <match url="*.scss"/>
          <action type="Rewrite" url="scss.php"/>
        </rule>
        <rule name="wordpress" patternSyntax="Wildcard">
          <match url="*"/>
          <conditions>
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true"/>
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true"/>
          </conditions>
          <action type="Rewrite" url="index.php"/>
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>

And... that's it! The only thing I had to do was change the theme, so it links to the scss file instead of the css file. A big shout-out to Bas Wildeboer for helping me to get the PHP-part done.

expand_less