Answer the question
In order to leave comments, you need to log in
How to add json of all files in c gulp-data directory?
Guys, help me add all json files to gulp-data for later use in twig templates.
Unfortunately, there is not much experience with gulp, I set it up once and it worked. And then I wanted to improve.
I do it like this:
'use strict';
var gulp = require('gulp'),
data = require('gulp-data'),
path = require('path'),
fs = require('fs'),
twig = require('gulp-twig'),
plumber = require('gulp-plumber'),
browserSync = require("browser-sync"),
reload = browserSync.reload;
var _GLOBAL_PATHS = {
build : 'app-public/',
source : 'app-source/'
}
var config = {
server: {
baseDir: _GLOBAL_PATHS.build
},
tunnel: true,
host: 'localhost',
port: 8080,
};
var PATHS = {
BUILD : {
html : _GLOBAL_PATHS.build
},
SOURCE : {
twig : _GLOBAL_PATHS.source + 'app-twig/*.twig',
},
WATCH : {
twig : _GLOBAL_PATHS.source + 'app-twig/**/*.twig',
}
};
/* ------------------------------------------------------------ */
// .....
gulp.task('twig:build', function () {
gulp.src(PATHS.SOURCE.twig)
.pipe(plumber())
/* тут пытаюсь решить свою задачу */
.pipe(
gulp.src('./app-source/app-data/*.json')
.pipe(data(function(file) {return JSON.parse(fs.readFileSync(file.path)); }))
)
/* -------------------- */
/* Page data - если указывать явно каждый файл, всё работает, но не удобно */
// .pipe(data(function(file) { return JSON.parse(fs.readFileSync('./app-source/app-data/Globals.json')); }))
// .pipe(data(function(file) { return JSON.parse(fs.readFileSync('./app-source/app-data/Menu.json')); }))
/* -------------------- */
.pipe(twig())
.pipe(plumber.stop())
.pipe(gulp.dest(PATHS.BUILD.html))
.pipe(reload({stream: true}));
});
Plumber found unhandled error:
Error in plugin "gulp-data"
Message:
SyntaxError: Unexpected token % in JSON at position 1
[02:17:44] Plumber found unhandled error:
Error in plugin "gulp-data"
Message:
SyntaxError: Unexpected token < in JSON at position 0
Answer the question
In order to leave comments, you need to log in
Since there is no answer, I decided to do this:
.pipe(data(function(file) { return JSON.parse(fs.readFileSync('./app-source/app-data/Globals.json')); }))
.pipe(data(function(file) { return JSON.parse(fs.readFileSync('./app-source/app-data/' + path.basename(file.path) + '.json')); }))
We glue all .json into data.json and drop it into PATHS.BUILD.html
gulp.task('twig:data', function () {
return gulp.src('./app-source/app-data/**/*.json')
.pipe(merge({
fileName: 'data.json',
edit: (json, file) => {
var filename = path.basename(file.path),
primaryKey = filename.replace(path.extname(filename), '');
var data = {};
data[primaryKey.toUpperCase()] = json;
return data;
}
}))
.pipe(gulp.dest(PATHS.BUILD.html));
});
.pipe(data(function(file) {
return JSON.parse(fs.readFileSync(`${PATHS.BUILD.html}/data.json`))
}))
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question