Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gulp: insert content from file into script

Tags:

gulp

I've a JavaScript file script.js like this:

var myArray = {"INSERT":"ARRAY"};

Further I've a array.json file like this:

{
    "Item1": "Text1",
    "Item2": "Text2"
}

I would like gulp to replace the array in the script.js with the content in the array.json file. How can I do that?

I've been looking at gulp-replace and have this example:

gulp.task('my-task', [], function () {
    return gulp.src(['script.js'])
     .pipe(replace('{"INSERT":"ARRAY"}', '{"MY":"OTHER_ARRAY"}'))
     .pipe(gulp.dest("dist.js"));
});

where I successfully replace the text, but instead of replacing with a static array, I need to read the array.json file instead and use this instead. I'm not sure how I can do that or if there are any better solutions to this? I've been looking at gulp-inject, but I'm not sure if this can be used in my case?

like image 506
dhrm Avatar asked Feb 23 '26 16:02

dhrm


1 Answers

Just read the file contents?

gulp.task('my-task', [], function () {
    var replacement = fs.readFileSync('path/to/file');
    return gulp.src(['script.js'])
     .pipe(replace('{"INSERT":"ARRAY"}', replacement))
     .pipe(gulp.dest("dist.js"));
});
like image 120
Felix Kling Avatar answered Feb 25 '26 19:02

Felix Kling