[Qiita] gulp-jade で JSON ファイルを変数に読み込む方法
jade でサイトを作成していると、共通情報は外部ファイルにまとめて記述したくなります。やはり jade なので、外部ファイルは JSON 形式にまとめておきたいところですね。
先に結論
gulp-data を使いましょう。 gulp-jade に使い方も紹介されてます。
gulp-data を使わない方法
公式の方法に辿り着く前に、ろくすっぽ調べずに自己流で JSON データをパースしてました…。 果たしてこの方法に需要があるのかどうか分かりませんが、試行錯誤の時間を無為にするのも悔しいので、まあ、こんな方法もあるよーということで、晒しておきます。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//- パースしたJSONデータを格納するグローバル変数 | |
- var data = {} | |
//- JSON 構文をパースしてグローバル変数の data にデータを格納する mixin | |
mixin json(name) | |
- var oldbuf = buf | |
- buf = [] | |
block | |
- data[name] = JSON.parse(buf.join('')) | |
- buf = oldbuf | |
//- 外部 JSON 情報の読み込み | |
+json('site') | |
include site.json | |
//- 呼び出し | |
h1: a(href=data.site.root) #{data.site.name} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//-data site.json | |
//- 呼び出し | |
h1: a(href=data.site.root) #{data.site.name} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
var gulp = require('gulp'); | |
var pug = require('gulp-pug'); | |
var data = require('gulp-data'); | |
gulp.task("pug", function(){ | |
return gulp.src("./*.pug") | |
.pipe(data(function(file) { | |
var json = {}; | |
String(file.contents).split("\n").forEach(function(line) { | |
if(line.match(/^\/\/\-\s*?data\s+?((\w+)\.json)$/)) { | |
json[RegExp.$2] = require("./" + RegExp.$1); | |
} | |
}); | |
return { data: json }; | |
})) | |
.pipe(pug({ | |
pretty: true | |
})) | |
.pipe(gulp.dest("./")) | |
; | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "サイトタイトル", | |
"root": "/" | |
} |
解説
jade 標準出力を横取りして JSON をパースしてます。
最後に読み込んだ JSON が標準出力されないよう、バックアップしていた buf
を書き戻してます。 buf
は jade の mixins で使われている内部変数ですので、あまり行儀の良いやり方ではありませんが…
強いてこの方法の利点を挙げれば
- gulpfile.js に 設定ファイルの記述なしに jade の構成ファイルの記述内で完結できる
- gulp-data が何らかの理由により使えない環境の代替となる
と言ったところでしょうか。
※この記事はQiitaとのマルチポストになります。