Skip to main content
Sheelah Brennan

How to Set up Pug File Linting with Gulp

Update (11/12/18)

The Pug file linting tool mentioned below, pug-linter, now supports a “fail on exit” mode and custom reporting options, which makes the custom Gulp lint reporter strategy below unneeded. See the gulp-pug-linter documentation for more details.

I recently set up Pug file linting for a Node.js/Express project at work that was already using Gulp. First of all, why linting? It's a great way to be able to detect any formatting errors or other code issues that may trigger bugs when working on new features. As a result, linting is a great process to kick off as part of builds and any automated continuous integration or deployment pipeline.

My goal was to have prettified lint output for any lint errors along with proper exit codes, meaning an exit code of zero for clean runs and non-zero for runs where errors were found. It's just way better having errors printed out in an easy-to-read way! Having previously set up Sass file linting with gulp-stylelint, which uses stylelint, I was already used to its prettified error reporting and wanted the same for Pug linting.

I found gulp-pug-linter, which uses the pug-lint CLI. “Perfect!” I thought. Then I discovered that I wouldn't be able to get the prettified error formatting using that Gulp plugin alone. Enter puglint-stylish, an error reporter that would give me the nicely formatted output I was looking for. I then set out to make these 2 tools work together.

The problem I faced with gulp-pug-linter was that I wanted to use a custom error reporter (puglint-stylish) but still have the Gulp lint task use proper exit codes. Since the option in gulp-pug-linter for using a custom error reporter was the same option used to configure errors to trigger the task to fail upon lint errors, it felt like I wouldn't be able to get my prettified output after all.

I later came up with a solution: write a custom pug lint reporter function for the Gulp task. This custom function, which acted as my own lint error reporter, both passed lint run output to puglint-stylish and set the task to fail upon any lint errors. Here's what I ended up with in my Gulpfile.js:

    gulp.task('pug-lint', function () {
      const plugin = 'gulp-pug-linter'
      const pugLintReporter = function (results) {
        pugLintStylish(results)
        if (results.length > 0) {
          this.emit('error', new util.PluginError(plugin, 'Failed with errors'))
        }
      }
      return gulp
        .src('app/views/**/*.pug')
        .pipe(pugLinter())
        .pipe(pugLinter.reporter(pugLintReporter))
    })