javascriptgulpgulp-watchjs-beautify

Prettify JS on save using js-beautify with Gulp


I am using js-beautify with Gulp to prettify JavaScript on save.

I am unable to use gulp.src and gulp.dest pipes. It was giving error

dest.on('unpipe', onunpipe);

So I used the following code and achieved the result I want.

gulp.task("jsbeautify", function () {
    const fs = require('fs');
    gulp.watch(config.srcTest).on("change", function (file) {
        console.log("Updating file");
        const destPath = file.path.replace(/\/[^/]*.js/g, " ");
        const fileContent = fs.readFileSync(file.path, "utf8");
        fs.writeFileSync(file.path, jsBeautify(fileContent, {indent_size: 2}));
    });
});

The documentation in js-beautify doesn't provide examples to modify or write to file. So I used fs.

Is there a better way to do it? Maybe using gulp.src with pipe.


Solution

  • Whatever you want to do with gulp, there's probably a package that already does it well.

    It's the case for beautifying using js-beautify with the gulp-jsbeautify package.

    To modify files in place using gulp, set the base option when calling gulp.src and use ./ as the destination.

    var gulp = require('gulp');
    var prettify = require('gulp-jsbeautifier');
    
    gulp.task('prettify', function() {
      return gulp.src(config.srcTest, {base: "./"})
        .pipe(prettify())
        .pipe(gulp.dest('./'));
    });
    
    gulp.task('watch', function() {
      gulp.watch(config.srcTest, ['prettify']);
    });
    

    Then calling gulp watch will start the watcher.

    The "beautifier options" are the same underscored options used by js-beautify. See the js-beautify docs for a list of them.

    All "beautifier options" placed in the root, are applied to CSS, HTML and JavaScript, unless there are no specific ones.

    The options given through parameters in gulp are merged with those given through files. The merge order is: default values, configuration file, parameters. Subsequent options overwrite the previous ones.

    This means that you can pass any default js-beautify options to the plugin directly in the gulp task.

    .pipe(prettify({
      indent_level: 4, // applied to CSS, HTML, JS
      js: {
        indent_level: 2 // applied to JS only
      }
    ))
    

    But I strongly advise you to put the options into a JSON formatted .jsbeautifyrc file at the root of your project.


    For more flexibility with gulp, see How can I write a simple gulp pipe function?