LoginSignup
51
50

More than 5 years have passed since last update.

【AngularJS】テンプレート(.html)を1ファイルにまとめたい!

Last updated at Posted at 2014-04-25

gulp版かきました: 【AngularJS】テンプレート(.html)を1ファイルにまとめたい! - gulp ver.

grunt-angular-templates

GruntでJSやCSSをビルドするとき,

  • ひとつにまとめて(concat
  • ちっちゃくして(uglifycssmin, htmlmin

少しでもページの読み込みを軽くしようとします,が….
AngularJSでDirectiveng-includeする用のテンプレートファイル(.htmlファイル)はどうしたらいいの?( ゚д゚)

  • 「jsファイルにHTMLをつらつら書いていくのはチョット…」
  • 「かと言ってバラバラのままだとリクエストが増えて重くなる…」

そんな時に便利なのがgrunt-angular-templatesです.

templates
 ┣ hoge.html
………
 ┣ fuga.html
 ┗ piyo.html

みたいな大量のテンプレートファイルを

templates.js
angular.module('app').run(["$templateCache", function($templateCache) {
  $templateCache.put("templates/hoge.html",
    // hoge.htmlのなかみ
  );
  ...
  $templateCache.put("templates/piyo.html",
    // piyo.htmlのなかみ
  );
}]);

のようにイイカンジのJSにまとめてくれます(これをふつうに読みこめばOK)

つかいかた

ふつうのつかいかた

Gruntfile.coffee
ngtemplates:
  # テンプレートを扱うAngularJSのモジュール名
  app:
    # テンプレートファイルたち
    src: 'templates/**.html',
    # 出力されるJS
    dest: 'javascripts/template.js',

基本は上のような感じ.注意点としては

  • 最初のappのところは自分のモジュール名にする

minifyしたい!

Gruntfile.coffee
ngtemplates:
  app:
    src: 'templates/**.html',
    dest: 'javascripts/template.js',
    options:
      # htmlminのオプションも使えるよ!
      htmlmin:
        collapseWhitespace: true

htmlminと同様のオプションが扱えるので,結構小さくできる.


ファイルパスとtemplateUrlを別にしたい!

Gruntfile.coffee
ngtemplates:
  app:
    # 実際にテンプレートが置いてあるディレクトリ
    cwd: 'app'
    # アプリで使用するURL
    src: 'templates/**.html',
    dest: 'javascripts/template.js',

上のようにしたら,app/templates以下のHTMLファイルがまとめられる(app以下ではない).

たとえば,app/src/templates以下のHTMLファイルをtemplates/**.htmlというURLで扱いたい場合は

Gruntfile.coffee
cwd: 'app/src'
src: 'templates/**.html'

のようになるので要注意!


useminと一緒につかいたい!

Gruntfile.coffee
ngtemplates:
  app:
    src: 'templates/**.html',
    dest: 'javascripts/template.js',
    options:
      usemin: 'javascripts/app.min.js'

としておいて,build時にconcatuglifyより手前で実行したらOK(ぼくはuseminPrepareの直後においてます:D).

※ 注意点

  • javascripts/app.min.jpのところはHTMLファイル中の<!-- build:js -->で指定しているファイル名を記述
  • ngtemplatesのほうのconcatオプションは使ったらダメらしい

Do not use the concat option, even though grunt-usemin generates a concat.generated object behind the scenes. Instead, use the usemin option to indicate the anticipated output filepath from grunt-usemin.


ほかにもいろんなオプションがあるみたいですが,僕が使うのはコレぐらいです.

サクサク動くアプリをGruntでイイ感じに自動化しながらつくろう!
これでみんなもモテモテだ!!!!! [要出典]

参考

51
50
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
51
50