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
.
- Open up a terminal window in the directory with gulpfile.js
- Enter
npm install require-strip-json-comments --save
- After installation, require the package in the gulpfile:
var requireJSON = require('require-strip-json-comments');
- Wherever there is a require for a JSON file that should allow comments, replace require with requireJSON. For example:
var config = requireJSON("./config.json");
- 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
.
- Open up a terminal window in the directory with gulpfile.js
- Enter
npm install gulp-strip-json-comments --save
- After installation, require the package in the gulpfile:
var stripJsonComments = require('gulp-strip-json-comments');
-
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).
- In the bottom right corner of the blue bar, click on JSON.
- 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!