[Qiita] gulp-pug v2.0 で JSON ファイルを変数に読み込む方法
jade は商標の問題から、pug に名前が変わりました。また、2016年6月23日時点で v2.0 がベータ版リリースされていますが、v1.11から いろいろと内部構成が変わっていて、以前に紹介した mixin で横取りする方法が使えなくなっていました。
素直に gulp-data を使った方が良さそうですが、ページ毎に適用する JSON ファイルを変更するような運用にしたいので、JSON ファイルの指定は gulpfile.js ではなく、pug ファイル側で指定したいところです。 pug 自体に外部 JSON ファイルをパースする機能があれば良いのですが、残念ながら現時点では自前で用意するしかなさそうです。
タスク側から pug に記述した JSON ファイルを取得する
pug 本体に手を加えるのは時間がかかりそうなので、手っ取り早く gulpfile.js のタスク処理側でカバーします。 ページ側に特定書式コメントの JSON ファイルのパスを指定しておき、タスクの gulp-data 経由で JSON ファイルを読み込むようにします。
pug コメントの後に続けて data path/to/filename.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
| { | |
| "name": "サイトタイトル", | |
| "root": "/" | |
| } |
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} |
pug コンパイルのタスクで、前述の 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
| '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("./")) | |
| ; | |
| }); |
これで 指定した JSON ファイルの内容を data.[ファイル名] のデータとして pug から参照できるようになりました。
※この記事はQiitaとのマルチポストになります。