Generating CSS styleguides with Grunt and KSS

The context

While working on a large-scale project, as a rule, there is a work division between programmers, designers and front-end developers. Programmers often ask front-end developers which CSS class should be used, e.g. for a blue button or any other component. Twitter’s Bootstrap is a common framework for many projects, and has a great documentation. This helps both groups during the development. However, what should a front-end developer do, if he or she does not have Bootstrap, but his/her own lightweight framework tailor-made for a particular website?

Of course, you can easily create an html page with all components. For sure you will remember to create different variations of every component, and update this page after every single change. Will you? :-)

Another solution is to generate a styleguide from the description of components in your CSS file (Less, SaaS). In this case, documentation will be visually closer to your code. Another asset of this solution is that anyone from your team may get the framework documentation, including available components and ways of their implementation.

There are few styleguide generators: DocumentCss, StyleDocco, KSS. In this post you will learn how to implement and use Knyle Style Sheets (KSS) generator in your Grunt project.

If you haven’t used NPM before, please check the Getting Started guide first.

If you haven’t used Grunt before, also check the Getting Started guide. It not only explains how to create a Gruntfile, but also how to install and use the Grunt plugins.

Once you’re familiar with NPM and Grunt, you may install plugins with this command:

npm install grunt grunt-cli grunt-contrib-connect grunt-contrib-watch grunt-shell kss --save-dev

grunt-contrib-connect will start local server, grunt-contrib-watch will be listening for changes in our CSS files, and grunt-shell will run kss-node command (installed with kss) in shell.

After installing packages in your package.json file you will find a section with devDependencies:

"devDependencies": {
    "grunt-cli": "^0.1.13",
    "grunt-contrib-connect": "^0.11.2",
    "grunt-contrib-watch": "^0.6.1",
    "grunt-shell": "^1.1.2",
    "kss": "^2.1.0"
}

After that, in Gruntfile.js configure connect, watch and shell tasks.

connect

connect: {
    options: {
        port: 9000,
        hostname: 'localhost',
        livereload: 35729,
        base: ['styles', 'kss-styleguide']
    },
    livereload: {
        options: {
            open: true
        }
    }
}

watch

watch: {
    styles: {
        files: ['styles/*.css'],
        tasks: ['shell:styleguide'],
        options: {
            nospawn: true,
            livereload: '<%= connect.options.livereload %>'
        },
    },
    livereload: {
        options: {
            livereload: '<%= connect.options.livereload %>'
        },
        files: []
    }
}

shell

shell: {
    styleguide: {
        options: {
            execOptions: {
                cwd: './node_modules/.bin'
            }
        },
        command: 'kss-node --placeholder "[modifier class]" --source ../../styles --destination ../../kss-styleguide --css /style.css'
    }
}

Don’t forget to register tasks from packages we’ve installed earlier. Then create a new task to start a local server:

grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.loadNpmTasks('grunt-shell');

grunt.registerTask('live', [
    'connect:livereload',
    'watch'
]);

The whole Gruntfile.js should look like this:

'use strict';
module.exports = function (grunt) {
    grunt.initConfig({
        // local server configuration
        connect: {
            options: {
                port: 9000,
                hostname: 'localhost',
                livereload: 35729,
                base: ['styles', 'kss-styleguide']
            },
            livereload: {
                options: {
                    open: true
                }
            }
        },
        // file changes watch configuration
        watch: {
            styles: {
                files: ['styles/*.css'],
                tasks: ['shell:styleguide'],
                options: {
                    nospawn: true,
                    livereload: '<%= connect.options.livereload %>'
                },
            },
            livereload: {
                options: {
                    livereload: '<%= connect.options.livereload %>'
                },
                files: []
            }
        },
        // shell task configuration
        shell: {
            styleguide: {
                options: {
                    execOptions: {
                        cwd: './node_modules/.bin'
                    }
                },
                // command for generating styleguide
                // flags for configuration are available here:
                // https://github.com/kss-node/kss-node#using-the-command-line-tool
                command: 'kss-node --placeholder "[modifier class]" --source ../../styles --destination ../../kss-styleguide --css /style.css'
            }
        },
    });

    // Requiered for grunt tasks
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-contrib-connect');
    grunt.loadNpmTasks('grunt-shell');

    grunt.registerTask('live', [
        // start local server
        'connect:livereload',
        // listen to changes in app files
        'watch'
    ]);
};

Now we have finished our configuration and can start with writing the styles. Let us create a file called style.css and styleguide.md in the styles folder. styleguide.md is a file with a styleguide overview. You can change the name of the file, but don’t forget to add --homepage <name> flag to kss-node command. In style.css we will create our styles and documentation. Please find the explanation below the code.

style.css

/*
Button

Buttons we are going to use on our pages. Here we are using inline Makrup.

:hover - hover highlight.
:active - active highlight.

Markup:
<a href="#" class="button {{modifier_class}}">this is button</a>

Styleguide 1
*/

.button {
    box-shadow:inset 0px 1px 0px 0px #ffffff;
    background-color:#f9f9f9;
    border:1px solid #dcdcdc;
    display:inline-block;
    cursor:pointer;
    color:#666666;
    font-family:Arial;
    font-size:15px;
    font-weight:bold;
    padding:6px 24px;
    text-decoration:none;
    text-shadow:0px 1px 0px #ffffff;
}

.button:hover {
    background-color:#e9e9e9;
}

.button:active {
    position:relative;
    top:1px;
}

EXPLANATION. We are describing our components with comments in a given file, as well as setting the structure of generated documentation. The first line (Button) is a title of a section, the second one is a description (Buttons we are going to use on our pages...).The third section concerns modifiers:

:hover - hover highlight.
:active - active highlight.

Modifiers are used for adding classes and pseudo-classes to our documentation. In the generated documentation we will find buttons with default styling, :hover state, :active state. You can also use classes as modifiers: .my-class - description of modifier.

We always need to provide html for our style. It is easy to do in the Markup: section. {{modifier_class}} refers to modifiers from previous section.

Markup:
<a href="#" class="button {{modifier_class}}">this is button</a>

There is an optional way of creating a markup, though. There is an option to add a markup in a separate file. Let’s create, for example, a file styles/templates/buttons.hbs with the following content:

<a href="#" class="button {{modifier_class}}">Link Button</a>
<button class="button {{modifier_class}}">Button Element</button>
<input type="button" class="button {{modifier_class}}" value="input[type='button']"/>

Then, change the Markup section as follows:

Markup: templates/buttons.hbs

Now we are done! Please run grunt live in a command line. If everything is fine at http://localhost:9000, you will get your first own-generated styleguide.

In this tutorial we were using a default styleguide template, but you can create your own one, or download a template from the GitHub:

You may even extend your template with helpers and Handlebars.

Here you can find related sites and articles:

Source Code

The source code is available here. Please download the archive, unpack it to any folder, and install the packages with npm install command. Start the project with the command grunt live and… have fun!