LoginSignup
4
4

More than 5 years have passed since last update.

Node.jsのmoduleをjsonにするgruntプラグインつくたー

Last updated at Posted at 2014-03-21

経緯

クライアント用にjsonでデータを用意しようと思ったけど、生のjsonを管理するとか苦痛なので、CoffeeScriptで書きたい。

さらに、Node.jsでゴニョゴニョしたデータを含めたかったので、Nodeで実行した結果をjsonにしたい。
例えば、画像データをData URI schemeにするとか、共通のデータを別ファイルにしておいて読み込むとか。

ということで、module.exportsをJSONに変換して出力するgruntプラグインつくりました。

内部的には単純にmodule.exportsをJSON.stringifyでJSONフォーマットな文字列に変換して出力しているだけです。

example

コンパイル対象のソース

target.json.coffee
'use strict'
fs = require 'fs'
delete require.cache[require.resolve './path/to/common.coffee']

module.exports =
  hoge: 'hoge'
  include: require './path/to/common.coffee'
  img: 'data:image/png;base64,' + fs.readFileSync __dirname + '/path/to/img.png', 'base64'

common.coffee
'use strict'

module.exports =
  fuga: 'fuga'

書きだしたjson

{"hoge":"hoge","include":{"fuga":"fuga"},"img":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAABGdBTUEAALGPC/xhBQAAAANQTFRF////p8QbyAAAAApJREFUCNdjYAAAAAIAAeIhvDMAAAAASUVORK5CYII="}

インストール

npm install exports2json -D

設定

オプションは今のところありません。

exports2json:
  expand: true
  cwd: 'path/to/src'
  src: [ '**/*.json.js', '**/*.json.coffee' ]
  dest: 'path/to/dest'
  ext: '.json'

github

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4