2015/03/12

[JavaScript][Grunt]grunt-contrib-jstを使ってtemplateをコンパイルする

先日、読み終わったBackbone.jsアプリケーション開発ガイドを読んで下のようにテンプレートを組んでいます。

<script type="text/template">
<!-- -->
</script>
ただ、これ、テンプレートが増えまくると、scriptタグが多発することになり、メンテ的によくない。

ので、これ、外部ファイルにして、可読性をあげようと下のようにできるのかなーっと思ったらできないみたい。
<script type="text/template" src="" >
で、どうするかというと、grunt-contrib-jstを使って一つのjsファイルにまとめる方法があるのようなので、方法を調査してみた。

まず、まとめたいhtmlファイル群のところまでディレクトリを移動して、下記のコマンドを打つ。(Gruntfile.js、package.json作成を忘れずに)
npm install grunt-contrib-jst --save-dev
その後、Gruntfile.jsを下のように修正。
'use strict';

module.exports = function (grunt) {

    grunt.initConfig({
        jst: {
          compile: {
            options: {
              templateSettings: {
                interpolate : /\{\{(.+?)\}\}/g
              }
            },
            files: {
              "../templates.js": ["./*.html"]
            }
          }
        }
    });
   
    grunt.loadNpmTasks('grunt-contrib-jst');
    grunt.registerTask('build', ['jst']);
 
};
修正後、下記コマンドを打ったら一個上のフォルダにtemplates.jsファイルができた。
grunt build

0 コメント:

コメントを投稿