I know that gulp require a vinyl source stream to work properly, but is there an easy way to use an already existant vinyl file or a json object instead of the well known gulp.src that only takes globs?
After several researches I did not found any good solution for that problem so I decided to share my solution with you.
That problem is solved in 2 steps
1: You need to convert what ever you want to pipe in gulp to a vinyl file. This can be done like so
const Vinyl = require('vinyl');
var vinyl = new Vinyl();
vinyl.cwd = '/';
vinyl.base = '/';
vinyl.path = '/yourfictivefilepath';
vinyl.contents = new Buffer(JSON.stringify(yourobject));
For more information about that step: https://github.com/gulpjs/vinyl
2: Create a stream out of your vinyl files
I found that those steps can be repetitive and can make code less readable so I decided to encapsulate those steps in an npm package that does this for you.
https://www.npmjs.com/package/gulp-to-stream
Since gulp uses vinyl files as input and actually uses some of its properties(such as .base
), it's inevitable to create vinyl files to make use of gulp. So I recommend this access to achieve your goal:
'use strict';
const gulp = require('gulp');
const header = require('gulp-header');//https://www.npmjs.com/package/gulp-header
gulp.task('default', function () {
gulp.src("a.json")//empty file
.pipe(header(JSON.stringify({a:1,b:2})))//inject your own content
.pipe(gulp.dest("dist/"))
});
Create a empty file a.json
and use it as source. Then inject your own content with gulp-header
and do whatever you want with it.
If you want to avoid extra files(a.json), try this:
'use strict';
const gulp = require('gulp');
const transform = require('gulp-transform');
const rename = require("gulp-rename");
gulp.task('default', function () {
return gulp.src("./gulpfile.js")
.pipe(transform(() => JSON.stringify({a:1,b:2})))
.pipe(rename("a.json"))
.pipe(gulp.dest("dist/"))
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With