LoginSignup
1

More than 5 years have passed since last update.

grunt-initでテンプレートをコンパイルしてファイルをコピーする

Posted at

grunt-initの処理の中心である、rootディレクトリ内のファイルをプロンプトで取得したデータでコンパイルしてコピーするやり方。

ざっくりコピー (init.copyAndProcess)

テンプレート・ディレクトリの内にあるrootディレクトリをざっくりとコピーする場合はinit.filesToCopyとcopyAndProcessを使う。

まずfilesToCopyで、rootディレクトリ内からrename.jsonの内容を反映したファイルリストを取得する。

rename.jsonでは、特定のファイルをコピーの対象から外したり、リネームさせるためのルールを記述する。

下記の設定ではrootディレクトリ内にある、src/js/main.jsを、取得した(または初期値 = init.processの第1引数)のデータのnameプロパティにリネームする設定と、dataディレクトリをコピーの対象から外している。

rename.json
{
  "src/js/main.js": "src/js/{%= name %}.js",
  "data/**/*": false
}

次に、取得したファイル・リストとプロンプトで取得データを引数にいれて、init.copyAndProcessを実行する。

template.js
exports.template = function(grunt, init, done) {
  init.process({
    "some" : "some property"
  }, [
    init.prompt('name')
  ], function(err, props) {
    var files = init.filesToCopy(props);
    init.copyAndProcess(files, props, {
      noProcess: ['my_templates/**/*','**/*.png','**/*.jpg','**/*.gif']
    });

    done();
  });
};

オプションのnoProcessに指定したファイルは、処理を通さずにコピーされる。上記の例だと、my_templatesディレクトリ内にあるファイルと、拡張子がpng、jpg、gifの画像ファイルが処理の対象外になる。バイナリファイルを処理してしまうと壊れてしまうので、noProcessに入れておく。また、テンプレートのままコピーしたい場合なども入れておく。

特定のテンプレートを元にコピー (grunt.template.processとgrunt.file.write)

特定のテンプレートをコピーする場合は、コピーしたいテンプレートを読みこんでコンパイルしたのちに、書き込み処理を行う。

具体的にはinit.srcpathをつかって、テンプレート・ディレクトリ内にあるrootディレクトリの中の対象のテンプレートのパスを取得して、grunt.file.readでファイルを読み込む。

その後にgrunt.template.processに読み込んだテンプレートとデータを渡してコンパイルする。
最後にgrunt.file.writeでコンパイルしたファイルを書き込む。

template.js
exports.template = function(grunt, init, done) {
  init.process({
    "some" : "some property"
  }, [
    init.prompt('name')
  ], function(err, props) {
    var temp = grunt.file.read(init.srcpath('src/index.html'));
    var compile = grunt.template.process(temp, {data: props, delimiters: 'init'});
    grunt.file.write('test/test.html', compile);

    done();
  });
};

おしまい

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