Develop a Hexo Theme with Gulp and Browsersync

Final Result

Hexo is a fast, simple&powerful blog framework. I have use Hexo for my personal blog for some time and recently I decide to {% post_link some-little-things-recently develop a theme for Hexo %}.

Browsersync is a awesome testing tool for front-end developer. It will synchronize all your behavior on different browsers or devices and save us a lot of time. There is no doubt that I will use Browsersync for all front-end develop work. This time no except.

The basic of developing a Hexo theme is to create some ejs templates and stylus files. Hexo will generate the content dynamically convert ejs templates to html and stylus to css. You need to modify stylus files and open browser to see the style. The question is that Browsersync need static html and css files. Yes, Hexo has a command called hexo generate which could generate static html and css files to public directory. We don't want to call hexo generate every time we modify the stylus files because the process will waste a lot of time. At the same time we don't want to modify the static css file in public directory directly because we will lose the modification afte hexo generate is called again. What we really want is after we modify stylus files Browsersync just works.

How to realize that? The answer is Gulp. Gulp is a front-end build system and Browsersync integrated with Gulp very well. The trick here is to use Gulp to generate and override the static css file every time we modify the stylus files. Talk is cheap. Let me show you the code.

Firstly install the dependencies:

npm install browser-sync gulp gulp-stylus --save-dev

Secondly create a file called gulpfile.js and add content below:

var gulp        = require('gulp'),
    browserSync = require('browser-sync').create(),
    stylus      = require('gulp-stylus');

gulp.task('serve', function() {
    // tell Browsersync serve the static directory
    browserSync.init({
        server: {
            baseDir: "../../public"
        }
    });
    // once stylus file is modified perform `stylus` task
    gulp.watch("./source/css/**/*.styl", ['stylus']);
});

gulp.task('stylus', function () {
  return gulp.src('./source/css/style.styl') // tell gulp the source stylus file
    .pipe(stylus()) // compile stylus to css
    .pipe(gulp.dest('../../public/css')) // output new css file to override
    .pipe(browserSync.stream()); // inject new css file
});

gulp.task('default', ['serve']);

Last preform gulp directly under your theme's directory. The magic thus happened. Browsersync will open a new tab in the default browser for you. Once you modify the stylus file and save the change Browsersync will reload automatically on all devices connected to the url. By the way don't forget to perform hexo generate to generate static files in public directory before perform gulp.

Happy coding!