【问题标题】:EJS getting JSON data with gulpEJS 使用 gulp 获取 JSON 数据
【发布时间】:2017-05-25 01:28:00
【问题描述】:

我正在使用 gulp 将我的 ejs 模板编译成一个 html 文件,我正在努力找出如何告诉它我的 json 数据文件在哪里。 当我尝试使用gulp-ejs 时,如下所示

gulp.task('ejs', function() {
  return gulp.src('src/views/pages/index.ejs')
    .pipe(ejs(
      { media: 'src/js/data/data.json' },
      { ext:'.html' }))
    .on('error', gutil.log)
    .pipe(gulp.dest('build/'))
    .pipe(browserSync.reload({
      stream: true
    }))
});

它将我想要的路径作为文字字符串。在 gulp 之外或在 gulp 中是否有其他方法可以将 json 数据传递给它?

【问题讨论】:

    标签: javascript json gulp ejs


    【解决方案1】:

    这对我来说是一个由两部分组成的问题,经过反复试验,我找到了解决方案。

    首先我错误地导入了我的 json 文件,我最终没有在 gulp 中导入它,但是当我稍后在我的 javascript 文件中导入它时,我做了如下操作:

    const media = require('src/js/data/data.json').media; // media was the name of the object I needed from the json file

    这让gulp-ejs 的 gulp 任务看起来像这样

    gulp.task('ejs', function() {
      return gulp.src('src/views/pages/index.ejs')
        .pipe(ejs(
          {},
          { ext:'.html' }))
        .on('error', gutil.log)
        .pipe(gulp.dest('build/'))
        .pipe(browserSync.reload({
          stream: true
        }))
    });
    

    如果有人在使用 gulp-ejs 并遇到问题,您必须留下一个空对象,您可以在其中导入任何数据,即使您不是。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-21
      • 2017-07-24
      • 1970-01-01
      • 1970-01-01
      • 2021-10-22
      • 2016-05-19
      • 2016-06-05
      • 2018-02-11
      相关资源
      最近更新 更多