LoginSignup
1
1

More than 5 years have passed since last update.

grunt-initの .writePackageJSON について

Posted at

こまったこと

grunt-initでは、package.jsonを吐き出す際にgrunt.writePackageJSONというメソッドを使う。
例えばこんな感じ。

template.js
grunt.writePackageJSON('package.json', {
    name: 'mogemoge',
    version: '0.1.0',
    dependencies: {
        async: '~0.2.8'
    }
})

ところがこのwritePackageJSONscriptsを指定しても反映されないことに気がついた。
npm test でテストとか、npm startでサーバー起動とか好きなのにー。

調べよう

というわけで、ソースを読む。(grunt-initの中身)
ack writePackageJSONしたところ、tasks/init.jsに患部があるらしい。

tasks/init.js
      writePackageJSON: function(filename, props, callback) {
        var pkg = {};
        // Basic values.                                                                  
        ['name', 'title', 'description', 'version', 'homepage'].forEach(function(prop) {
          if (prop in props) { pkg[prop] = props[prop]; }
        });
        // Author.                                                                        
        var hasAuthor = Object.keys(props).some(function(prop) {
          return (/^author_/).test(prop);
        });
        if (hasAuthor) {
          pkg.author = {};
          ['name', 'email', 'url'].forEach(function(prop) {
            if (props['author_' + prop]) {
              pkg.author[prop] = props['author_' + prop];
            }
          });
        }
(以下略)

こんなかんじで、どうやら与えたオブジェクトをまるっと書きだすのではなく、
決まったプロパティだけ選んでちまちまjsonにしているみたい。まめだのう。
しかしそれならscriptsもプロパティに入れといて欲しい。。

そして公式も読むと、以下のような記述が。

Project Scaffolding - Grunt: The JavaScript Task Runner

Save a package.json file in the destination directory. The callback can be used to post-process properties to add/remove/whatever.

init.writePackageJSON(filename, props[, callback])

ふむふむ。コールバックを使うとパラメータを少し弄って出力できるのね。
そんなわけで以下のようなコードを試した。

template.js
var pkg = {
    name: 'mogemoge',
    version: '0.1.0',
    dependencies: {
        async: '~0.2.8'
    },
    scripts: {
        test: 'NODE_ENV=test mocha',
        start: 'node server'
    }
};

// write package.json                                                             
init.writePackageJSON('package.json', pkg, function (pkg, props) {
    pkg.scripts = props.scripts;
    return pkg;
});

これで無事、scriptsも含まれたpackage.jsonを出力できますよ、と。

まとめ

writePackageJSON は、ちゃっかりbower.jsonの出力にも使えたりするので、
もうすこし柔軟なメソッドなのかと思ってたけど、案外けちくさかった。

ちなみに、scripts.testについては、
grunt-initのpropsの方でnpm_testを設定しとくと、勝手に入るみたい。
testしか使わないならこちらでもいいかもね。

1
1
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
1
1