LoginSignup
6
8

More than 5 years have passed since last update.

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

Posted at

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

gulp-angular-templatecache

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

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

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

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

そんな時に便利なのがgulp-angular-templatecacheです.

.
├── app
│   └── assets
│       ├── javascripts
│       └── templates
│           ├── hoge.html
│           └── fuga.html

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

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

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

つかいかた

ふつうのつかいかた

gruntfile.babel.js
import templateCache from "gulp-angular-templatecache";

gulp.task("build:templates", () => {
  return gulp.src('app/templates/**/*.html')
    .pipe(templateCache({module: "myApp"}))
    .pipe(gulp.dest("dist"));
});

基本は上のような感じ.注意点は「templateCacheのmoduleオプションは自分のangularアプリのモジュール名にする」ことです.
app/javascripts/constants.jsに定義しておいてimportしてくると綺麗ですね.

export const appName = "myApp";
import {appName} from "./app/javascripts/constants";

minifyしたい!

何もせずともminify済みのが出てきます.


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

たとえば,app/assets/templates以下のHTMLファイルをtemplates/**.htmlというURLで扱いたい場合,下記のいずれかのオプションを追加すればOK.

  • prefix: "templates"
  • base: "app/assets"

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

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

参考

6
8
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
6
8