Using Comments in Gulp JSON configuration files

Tech

March 29, 2018 2 min read

My team currently uses Gulp for project deployment, with fairly complex tasks involving confirguration files in JSON that are pulled in with both require and gulp.src. We needed to be able to add comments to our JSON files to document the structure as it changed over time.

Using JSON comments with require

The first challenge was to allow JSON comments in a file being pulled in with require. I used the npm package require-strip-json-comments.

  1. Open up a terminal window in the directory with gulpfile.js
  2. Enter npm install require-strip-json-comments --save
  3. After installation, require the package in the gulpfile: var requireJSON = require('require-strip-json-comments');
  4. Wherever there is a require for a JSON file that should allow comments, replace require with requireJSON. For example: var config = requireJSON("./config.json");
  5. Use the config variable as usual.

Using JSON comments with gulp.src

The second challenge was to allow JSON comments in a file being pulled in with gulp.src. I used the npm package gulp-strip-json-comments.

  1. Open up a terminal window in the directory with gulpfile.js
  2. Enter npm install gulp-strip-json-comments --save
  3. After installation, require the package in the gulpfile: var stripJsonComments = require('gulp-strip-json-comments');
  4. Wherever a JSON file is being pulled in with gulp.src, add the following as the first pipe: .pipe(stripJsonComments()). For example:

    gulp.task('default', () =>
    gulp.src('src/config.json')
        .pipe(stripJsonComments())
        .pipe(gulp.dest('dist'))
    );
    

Getting rid of Visual Studio Code errors

We use Visual Studio Code as our editor. The above allowed us to add comments to our JSON files used by Gulp, but VS Code gave us error when adding the comments. The following disables these errors per file (it is also possible to do it for all files, but in our case there were JSON files outside of Gulp that needed to throw those errors).

  1. In the bottom right corner of the blue bar, click on JSON.
  2. A "Select Language Mode" will appear. Type jsonc and press Enter. (If you would like to disable this for all JSON files, select "Configure File Association for '.json'..." instead.)

Share

Think others might enjoy this post? Share it!

Comments

I'd love to hear from you, let me know your thoughts!