Compile all angular templates to one js file

2.4k Views Asked by At

I am trying to compile all angulara templates into a single js file. Something like what ember does with ember-cli.

So I successfully managed to minify and concat all the javascript files. I have just 2 files now vendor.js and application.js and whole lot of template files which I want to cram into templates.js.

How do I go about it? If some one could give step by step explanation, please. Any links would be appreciated too. Surprisingly there is no information about this anywhere.

I am using mimosa as build tool, it seemed to me the easiest. Here is my mimosa config:

exports.config = {
  modules: [
  "copy",
  "stylus",
  "minify-css",
  "minify-js",
  "combine",
  "htmlclean",
  "html-templates"
  ],
  watch: {
    sourceDir: "app",
    compiledDir: "public",
    javascriptDir: "js",
    exclude: [/[/\\](\.|~)[^/\\]+$/]
  },
  vendor: {
    javascripts: "vendor/js"
  },
  stylus: {
    sourceMap: false
  },
  combine: {
    folders: [
    {
      folder:"vendor/js",
      output:"vendor.js",
      order: [
      "angular.js"
      ]
    },
    {
      folder:"js",
      output:"main.js",
      order: [
      "application/main.js"
      ]
    }
    ]
  },
  htmlclean: {
    extensions:["html"]
  },
  htmlTemplates: {
    extensions: ["tpl"]
  },
  template: {
    outputFileName: "templates"
  }
}

It does generate templates.js file without any errors. But when I link it, angular spits a bunch of errors.

Once compiled, how do I actually call those templates from ng-include and from the route provider? I assume that it is the same as I would call a script template using the id which in my case is derived from template original file name, right? Maybe I am missing some important steps.

The build tool is not important here although desirable. If some one could show how to do it manually without a build tool I would figure out the rest.

Thanks.

1

There are 1 best solutions below

3
On BEST ANSWER

I'm using Gulp as my build tool, and in that, there's a plugin gulp-angular-templatecache which pre-compiles and registers all templates for your module in the angular $templateCache - no changes are required to any of the calling code to use these. EDIT: The Angular documentation for $templateCache explains how the templateCache works.

It might be worth reading through the documentation for gulp-angular-templatecache to see how that pre-populates the $templateCache to see if you can crib something that would work with your build process.

Here's my gulp task that does the job:

var templateCache = require('gulp-angular-templatecache');

gulp.task('buildjstemplates', function () {
  return gulp.src(['public/javascripts/app/**/*.html'])
  .pipe(templateCache({module: 'app'}))
  .pipe(gulp.dest('public/javascripts/app/'));
});