Gulp using gulp-jade with gulp-data

允我心安 提交于 2020-01-01 07:22:08

问题


I'm trying to use gulp-data with gulp-jade in my workflow but I'm getting an error related to the gulp-data plugin.

Here is my gulpfile.js

var gulp = require('gulp'),
  plumber = require('gulp-plumber'),
  browserSync = require('browser-sync'),
  jade = require('gulp-jade'),
  data = require('gulp-data'),
  path = require('path'),
  sass = require('gulp-ruby-sass'),
  prefix = require('gulp-autoprefixer'),
  concat = require('gulp-concat'),
  uglify = require('gulp-uglify'),
  process = require('child_process');

  gulp.task('default', ['browser-sync', 'watch']);

  // Watch task
  gulp.task('watch', function() {
    gulp.watch('*.jade', ['jade']);
    gulp.watch('public/css/**/*.scss', ['sass']);
    gulp.watch('public/js/*.js', ['js']);
  });

  var getJsonData = function(file, cb) {
    var jsonPath = './data/' + path.basename(file.path) + '.json';
    cb(require(jsonPath))
  };

  // Jade task
  gulp.task('jade', function() {
    return gulp.src('*.jade')
    .pipe(plumber())
    .pipe(data(getJsonData))
    .pipe(jade({
      pretty: true
    }))
    .pipe(gulp.dest('Build/'))
    .pipe(browserSync.reload({stream:true}));
  });

  ...

  // Browser-sync task
  gulp.task('browser-sync', ['jade', 'sass', 'js'], function() {
    return browserSync.init(null, {
    server: {
      baseDir: 'Build'
    }
  });
});

And this is a basic json file, named index.jade.json

{
  "title": "This is my website"
}

The error I get is:

Error in plugin 'gulp-data'
[object Object]

回答1:


You are getting error because in getJsonData you pass required data as first argument to the callback. That is reserved for possible errors.

In your case the callback isn't needed. Looking at gulp-data usage example this should work:

.pipe(data(function(file) {
  return require('./data/' + path.basename(file.path) + '.json');
}))

Full example:

var gulp = require('gulp');
var jade = require('gulp-jade');
var data = require('gulp-data');
var path = require('path');
var fs   = require('fs');

gulp.task('jade', function() {
  return gulp.src('*.jade')
    .pipe(data(function(file) {
      return require('./data/' + path.basename(file.path) + '.json');
    }))
    .pipe(jade({ pretty: true }))
    .pipe(gulp.dest('build/'));
});

Use this if you're running the task on gulp.watch:

.pipe(data(function(file) {
  return JSON.parse(fs.readFileSync('./data/' + path.basename(file.path) + '.json'));
}))


来源:https://stackoverflow.com/questions/27313107/gulp-using-gulp-jade-with-gulp-data

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!