Coder Social home page Coder Social logo

grunt-angular-templates's Introduction

grunt-angular-templates

Build Status Dependencies devDependencies

Speed up your AngularJS app by automatically minifying, combining, and automatically caching your HTML templates with $templateCache.

Here's an example of the output created by this task from multiple .html files:

angular.module('app').run(["$templateCache", function($templateCache) {
  $templateCache.put("home.html",
    // contents for home.html ...
  );
  ...
  $templateCache.put("src/app/templates/button.html",
    // contents for button.html
  );
}]);

Then, when you use ng-include or templateUrl with $routeProvider, the template is already loaded without an extra AJAX request!

Table of Contents

Installation

This plugin requires Grunt ~0.4.0

Usemin integration requires grunt-usemin ~2.0.0

Install the plugin:

$ npm install grunt-angular-templates --save-dev

Enable the plugin within your Gruntfile:

grunt.loadNpmTasks('grunt-angular-templates');

Options

angular

Global namespace for Angular.

If you use angular.noConflict(), then set this value to whatever you re-assign angular to. Otherwise, it defaults to angular.

bootstrap

Callback to modify the bootstraper that registers the templates with $templateCache.

By default, the bootstrap script wraps function($templateCache) { ... } with:

angular.module('app').run(['$templateCache', ... ]);

If you want to create your own wrapper so you register the templates as an AMD or CommonJS module, set the bootstrap option to something like:

bootstrap: function(module, script) {
  return 'module.exports[module] = ' + script + ';';
}

concat

Name of concat target to append the compiled template path to.

This is especially handy if you combine your scripts using grunt-contrib-concat or grunt-usemin.

htmlmin

Object containing htmlmin options that will significantly reduce the filesize of the compiled templates.

Without this, the HTML (whitespace and all) will be faithfully compiled down into the final .js file. Minifying that file will only cut down on the Javascript code, not the HTML within the strings.

Note - this does incur a performance cost. Simply leave out this option to prevent minificaiton.

I recommend using the following settings for production:

htmlmin: {
  collapseBooleanAttributes:      true,
  collapseWhitespace:             true,
  keepClosingSlash:               true, // Only if you are using SVG in HTML
  removeAttributeQuotes:          true,
  removeComments:                 true, // Only if you don't use comment directives!
  removeEmptyAttributes:          true,
  removeRedundantAttributes:      true,
  removeScriptTypeAttributes:     true,
  removeStyleLinkTypeAttributes:  true
}

module

String of the angular.module to register templates with.

If not specified, it will automatically be the name of the ngtemplates subtask (e.g. app, based on the examples below).

prefix

String to prefix template URLs with. Defaults to ''

If you need to use absolute urls:

ngtemplates: {
  app: {
    options: {
      prefix: '/'
    }
  }
}

If you serve static assets from another directory, you specify that as well.

source

Callback to modify the template's source code.

If you would like to prepend a comment, strip whitespace, or do post-processing on the HTML that ngtemplates doesn't otherwise do, use this function.

append

Boolean to indicate the templates should be appended to dest instead of replacing it. Normally grunt-angular-templates creates a new file at dest. This option makes it append the compiled templates to the dest file rather than replace its contents. This is just a useful alternative to creating a temporary dest file and concatting it to your application.

standalone

Boolean indicated if the templates are part of an existing module or a standalone. Defaults to false.

  • If the value is false, the module will look like angular.module('app'), meaning app module is retrieved.
  • If the value is true, the module will look like angular.module('app', []), meaning app module is created.

url

Callback to modify the template's $templateCache URL.

Normally, this isn't needed as specifying your files with cwd ensures that URLs load via both AJAX and $templateCache.

usemin

Path to <!-- build:js [path/to/output.js] --> usemin target

This should be the output path of the compiled JS indicated in your HTML, such as path/to/output.js shown here.

quotes

Use single or double quotes to wrap the template strings

Defaults to 'double', other option is 'single'

Usage

Compiling HTML Templates

After configuring your ngtemplates task, you can either run the task directly:

$ grunt ngtemplates

Or, bake it into an existing task:

grunt.registerTask('default', [ 'jshint', 'ngtemplates', 'concat' ]);

Including Compiled Templates

Finally, you have to load the compiled templates' .js file into your application.

Using HTML

<script src="templates.js"></script>

Using Grunt's concat task:

This is my personal preference, since you don't have to worry about what the destination file is actually called.

concat:   {
  app:    {
    src:  [ '**.js', '<%= ngtemplates.app.dest %>' ],
    dest: [ 'app.js' ]
  }
}

Using the following HTML as an example:

<!-- build:js dist/vendors.js -->
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/angular-resource/angular-resource.js"></script>
<!-- endbuild -->

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.

ngtemplates:  {
  app:        {
    src:      '**.html',
    dest:     'template.js',
    options:  {
      usemin: 'dist/vendors.js' // <~~ This came from the <!-- build:js --> block
    }
  }
}

Note: Earlier versions of grunt-usemin (correctly, in my opinion) would have generated a concat['dist/vendors.js'] object for each build section in the HTML. Now, because there's a single concat.generated object with all JS/CSS files within it, I'm back-tracking the proper concat target for you.

Examples

Register HTML Templates in app Module

ngtemplates:  {
  app:        {
    src:      '**.html',
    dest:     'templates.js'
  }
}

Register Relative Template URLs

Normally, your app, templates, & server are in separate folders, which means that the template URL is different from the file path.

ngtemplates:  {
  app:        {
    cwd:      'src/app',
    src:      'templates/**.html',
    dest:     'build/app.templates.js'
  }
}

This will store the template URL as templates/home.html instead of src/app/templates/home.html, which would cause a 404.

Minify Template HTML

Simply pass the same options as the htmlmin task:

ngtemplates:    {
  app:          {
    src:        '**.html',
    dest:       'templates.js',
    options:    {
      htmlmin:  { collapseWhitespace: true, collapseBooleanAttributes: true }
    }
  }
}

Or, if you already have an existing htmlmin task, you can reference it:

ngtemplates:    {
  app:          {
    src:        '**.html',
    dest:       'templates.js',
    options:    {
      htmlmin:  '<%= htmlmin.app %>'
    }
  }
}

Customize Template URL

Suppose you only use ngtemplates when on production, but locally you serve templates via Node, sans the .html extension.

You can specify a url callback to further customize the registered URL:

ngtemplates:  {
  app:        {
    src:      '**.html',
    dest:     'templates.js',
    options:  {
      url:    function(url) { return url.replace('.html', ''); }
    }
  }
}

Customize Output

Some people like AMD & RequireJS and would like wrap the output in AMD or something else (don't ask me why!):

ngtemplates:      {
  app:            {
    src:          '**.html',
    dest:         'templates.js',
    options:      {
      bootstrap:  function(module, script) {
        return 'define(' + module + ', [], function() { return { init: ' + script + ' }; });';
      }
    }
  }
}

You will be able to custom everything surrounding $templateCache.put(...).

Changelog

  • v1.1.0 - Added the merge option to allow templates to maintain directory structure if set to false (#114)
  • v1.0.4 - Updated html-minifier to 2.1.2 (#162)
  • v1.0.3 - Fixes issue with using usemin without uglify (#153)
  • v1.0.2 - Fixes issue with escaping carriage returns (#147), Fixes issue with escaping backslashes (#146)
  • v1.0.1 - Log error instead of warning when minify fails (#139)
  • v1.0.0 - Updated unit tests for performance and bumps dependency versions (#143)
  • v0.6.0 - Adds quotes options to allow wrapping in single instead of double quotes (#142)
  • v0.5.9 - Fixes over-matching on cwd when expand:true
  • v0.5.8 - Fixes cwd being part of the $templateCache string when expand:true (#134), Added verbose logging for minify (#136)
  • v0.5.7 – Improve error messages (#100)
  • v0.5.6 – Updated html-minifier to correct whitespace issues. (96)
  • v0.5.5 – Add append option to concat, not overwrite the dest. (#89)
  • v0.5.4 – Specifying an invalid usemin option still creates file (#84)
  • v0.5.3 – Fix bug with Underscore templates (#79)
  • v0.5.2 – Fix usemin matching issue on Windows (#80)
  • v0.5.1 – Add usemin option form v0.4.10
  • v0.5.0 – Works with grunt-usemin (#44)
  • v0.4.10 – Add usemin option
  • v0.4.9 – Improve prefix and support for URLs (#57)
  • v0.4.8 – Compiled assets are JSHint-able (#58)
  • v0.4.7 – Fix bug for when htmlmin is not an Object (#56)
  • v0.4.6 – Add prefix option for easier URL prefixes (#53)
  • v0.4.5 – Attempt to better normalize templates based on current OS (#52)
  • v0.4.4 – Fixed regression caused by htmlmin (#54)
  • v0.4.3 - options.concat targets on Windows convert / to \\. #48
  • v0.4.2 - Fix for using grunt-env to change environments. Thanks to @FredrikAppelros (#20)
  • v0.4.1 – Fix bug with empty files.
  • v0.4.0 – Complete rewrite.
  • v0.3.12 – Whoops, forgot to make htmlmin a regular dependency. Thanks @rubenv (#37)
  • v0.3.11 – Add htmlmin option that supports both an { ... } and <%= htmlmin.options %> for existing tasks.
  • v0.3.10 – Fix unknown concat target bug on windows, thanks to @trask (#31)
  • v0.3.9 – Allow the creation of a new module via module.define, thanks to @sidwood (#28)
  • v0.3.8 – Fix error that occurs when adding 0-length files, thanks to @robertklep (#27)
  • v0.3.7 – Add noConflict option to work with angular.noConflict, thanks to @mbrevoort (#26)
  • v0.3.6 – Fix issue with dading to concat task when it's an array, thanks to @codefather (#23)
  • v0.3.5 – Preserver line endings in templates, thanks to @groner (#21)
  • v0.3.4 – Attempt to fix a bug with Path, thanks to @cgross (#19)
  • v0.3.3 – Add concat option for automatically adding compiled template file to existing concat (or usemin-created) task, thanks to @cgross (#17)
  • v0.3.2 – Add module option for setting which module the templates will be added to, thanks to @sidwood (#20)
  • v0.3.1 – Add prepend option for modifying final $templateCache IDs, thanks to @mbarchein. (#16)
  • v0.3.0 – BC break - Templates are added to an existing module (e.g. myapp) rather than being their own myapp.templates module to be manually included, thanks to @geddesign. (#10)
  • v0.2.2 – Escape backslashes, thanks to @dallonf. (#9)
  • v0.2.1 – Remove ./bin/grunt-angular-templates. No need for it!
  • v0.2.0 – Update to Grunt 0.4, thanks to @jgrund. (#5)
  • v0.1.3 – Convert \\ to / in template IDs (for on win32 systems) (#3)
  • v0.1.2 – Added NPM keywords
  • v0.1.1 – Fails to combine multiple templates. Added directions to README on how to integrate with AngularJS app. Integrated with TravisCI
  • v0.1.0 – Released to NPM

License

Copyright (c) 2013 Eric Clemmons Licensed under the MIT license.

Bitdeli Badge

grunt-angular-templates's People

Contributors

aaani avatar christianrondeau avatar christopher-ramirez avatar dahmian avatar dallonf avatar doowb avatar ericclemmons avatar eulergammaelliott avatar evilaliv3 avatar fupslot avatar geddski avatar groner avatar hvdb avatar ilkelma avatar jgrund avatar kimjoar avatar mbarchein avatar mbrevoort avatar robertklep avatar rubenv avatar sahat avatar shahata avatar sidwood avatar terraflubb avatar thorn0 avatar timruffles avatar trask avatar underscorebrody avatar vvakame avatar yaru22 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

grunt-angular-templates's Issues

No empty array parameter in the module

The generated code for the module creation do not add the empty array necessary to create a new module, is it a desired behavior ? :

Generated code :

angular.module('app').run(["$templateCache", function($templateCache) {
  ...
}

Should include an empty array :

angular.module('app',[]).run(["$templateCache", function($templateCache) {
   ...
}

Without the empty array a "Module Unavailable" error is raised
http://docs.angularjs.org/error/$injector:nomod

Add CONTRIBUTORS section

Several awesome people have been helping on the project, so it'd be good to showcase them.

@cgross mentioned a CONTRIBUTORS.md file, but I'd rather put them in the README so they're not hidden away.

(Side note, use git log --authors or similar, since Github isn't 100% accurate)

Output truncated on windows

When running the task on Windows (using a VM) it cuts off the last part of the file. See the output here: http://pastebin.com/FvijUm89 It seems to happen regardless of HTML min options.

It works fine on Mac

My config is:

ngtemplates: {
    app: {
        cwd: 'PIM.Web/',
        src: 'content/app/partials/**/*.html',
        dest: 'PIM.Web/content/app/partials/compiled-templates.js',
        options: {
            module: 'pimApp',
            prefix: '/',
            htmlmin: {
                collapseBooleanAttributes: true,
                collapseWhitespace: true,
                removeAttributeQuotes: true,
                removeComments: true,
                removeEmptyAttributes: true,
                removeRedundantAttributes: true,
                removeScriptTypeAttributes: true,
                removeStyleLinkTypeAttributes: true
            }
        }
    }
},

ngtemplates task Warning: Object.keys called on non-object

Trying to run grunt build on a Yeoman scaffolded app with grunt-angular-templates as one of the tasks, generates the following errors:

>> Tasks directory "grunt-angular-templates" not found.

Also gives the following error:

Running "ngtemplates:TestApp" (ngtemplates) task
Warning: Object.keys called on non-object Use --force to continue.

Isolated run command: grunt ngtemplates:TestApp

Link to TestApp below:
Github repo

I'm not sure what is causing these errors.

Split into Grunt task and NPM module

Please consider splitting this plug-in into an NPM module and the Grunt plug-in itself. In this way it can be used without having to use Grunt if desired.

Embed ng-include

Would be awesome if you could read the ng-include src tag and embed that file in place of the tag. Thanks.

Add prefix option for the template IDs

I'm using $locationProvider.html5Mode(true), so my templates have to be absolute, not relative. I tried using src: '/views/*.html', but it didn't work.

In the end, I couldn't figure out how to do it, so I used grunt-angular-inline-templates. They have a prefix options, which makes it trivial to solve this issue (https://github.com/wmluke/grunt-inline-angular-templates#optionsprefix).

I'm not sure if there's another way to solve my issue but, if not, adding this option sounds easy and good enough. If you agree, I'd be happy to send a pull request. What do you think?

Warning with watch

I am using this with grunt-contrib-watch and I am getting this warning:

Running "ngtemplates:app" (ngtemplates) task Warning: Object function (expected) { return _this.evaluateAssertion(assertProvider, true, this, expected); } has no method 'map'

The proceeding grunt tasks are not being run, so if I stop the watcher and run grunt ngtemplates manually it will work just fine.

Any idea if this is a bug or I am doing something wrong?

How to specify module name

The default script looks like:

angular.module('app').run(['$templateCache', function($templateCache) {
   ...
});

Is there some possibility to rename the module name to something else?

I know that I could include this to my app as dependency, but I like to rename it.

Thanks!

Should be able to exclude files from src.

You should be able to add paths to ignore to the src option.

For example my project has a a folder app/assets/libs that I want to ignore.

My work around is set src: ['app/A//*.html', 'app/B//.html'].
But what want is src: ['!app/assets/', 'app/__/.html']

Thanks.

task hangs on parse error when certain letters are used

in my template I have a line:

<h2 ng-model="item.description" ui-tree-keyboard-suspend</h2>

and it makes ngtamplates hang. If no --verbose is used it hangs the entire terminal window - I don't know if it's normal or not.

I checked some variations:

<h2 foo-bar="anything" foo-bar-baz</h2>

does not hang - i get: Warning: Parse Error: <h2 foo-bar="anything" foo-bar-baz</h2> Use --force to continue.

<h2 foo-bar="anything" foo-bar-suspend</h2>

takes slightly more time to execute but it finishes in second or two - i get: Warning: Parse Error: <h2 foo-bar="anything" foo-bar-suspend</h2> Use --force to continue.

<h2 foo-bar="anything" foo-keyboard-suspend</h2>

takes about 10s to execute.

the entire:

<h2 ng-model="item.description" ui-tree-keyboard-suspend</h2>

takes more than 5 minutes (I killed the process).

Seems like the longer the attribute, the more time it takes to ensure it is a parsing error.
I Also checked it with or without dashes - does not seem to make much difference.

I mixed words:

<h2 ngmodel="item.description" uitreekeyboardsuspend</h2>

also takes a lot, but both

<h2 ngmodel="item.description" uitreekeyboardbar</h2>

and

<h2 ngmodel="item.description" uitreekeyfoobar</h2>

take nothing at all.
Hm... suspend?

Add usemin option

From @pheuter:

@ericclemmons In my case, I am generating two javascript files, vendor.js and application.js. When concatenating ng-templates, I need to append solely to application.js. The error I was running into was due to the templates file being concatenated to both files and that caused errors.

// build:js(.) javascripts/vendor.js

// build:js(.) javascripts/application.js

In which case, the jump to 0.5.0 may not be warranted (whoops!), because this solution can let someone specify usemin: 'javascripts/application.js' to target that specific dest.

concat is useful if you have a specific concat task, but trying to target what usemin generates for concat is annoying at best.

Standalone documentation is backwards in readme

The explanation in the readme is currently the opposite of how the code works (which is very confusing!). It reads:

If the value is true, the module will look like angular.module('app'), meaning app module is retrieved.
If the value is false, the module will look like angular.module('app', []), meaning app module is created.

This is saying that if the templates are standalone they will retrieve an existing app. If the templates are not standalone (default) they will create a new angular app.
They should read:

If the value is true, the module will look like angular.module('app', []), meaning app module is created.
If the value is false, the module will look like angular.module('app'), meaning app module is retreived.

Grunt 0.4 Release

I'm posting this issue to let you know that we will be publishing Grunt 0.4 on Monday, February 18th.

If your plugin is not already Grunt 0.4 compatible, would you please consider updating it? For an overview of what's changed, please see our migration guide.

If you'd like to develop against the final version of Grunt before Monday, please specify "grunt": "0.4.0rc8" as a devDependency in your project. After Monday's release, you'll be able to use "grunt": "~0.4.0" to actually publish your plugin. If you depend on any plugins from the grunt-contrib series, please see our list of release candidates for compatible versions. All of these will be updated to final status when Grunt 0.4 is published.

Also, in an effort to reduce duplication of effort and fragmentation in the developer community, could you review the grunt-contrib series of plugins to see if any of your functionality overlaps significantly with them? Grunt-contrib is community maintained with 40+ contributors—we'd love to discuss any additions you'd like to make.

Finally, we're working on a new task format that doesn't depend on Grunt: it's called node-task. Once this is complete, there will be one more conversion, and then we'll never ask you to upgrade your plugins to support our changes again. Until that happens, thanks for bearing with us!

If you have any questions about how to proceed, please respond here, or join us in #grunt on irc.freenode.net.

Thanks, we really appreciate your work!

I don't understand the base option

If I have a config like this

ngtemplates: {
            'templates': {
                options: {
                    base: 'partials/'
                },
                src: ['build/tmp/partials/*.html'],
                dest: 'build/js/templates.js'
            }
        }

I need the reference to the partials to be partials/home.html because that's the way my code is written.

Instead I get references like this build/tmp/partials/home.html . I've tried every base configuration I can think of.

I'm copying all the templates over when I minify the html so that's why it's in tmp directory.

When I think of base I don't think of a relative physical base path. I think of a string version of the path the html should be under.

I shouldn't be able to put things like '../../' for base and get a physical path. That would never make sense.

NodeJSProjects/myproject/build/tmp/partials/home.html

Let's say you have your public directory mapped using express. You load partials from /partials/home.html . When you go to do your build, all your template cache paths are public/partials/home.html because they are under the public directory. You should be able to say /partials.

silent failure with unhelpful message if "dest" is not a string (e.g. an array)

let me preface this by saying it's completely my own fault, but I lost a fair bit of time looking at my configuration before realizing my problem (since at a glance it appeared my configuration matched the examples).

consider this ngtemplates configuration:

        //ng-templates
        ngtemplates: {
            app: {
                src: ['assets/views/*.html'],
                dest: ['template.js']
            }

running grunt:

$ grunt --verbose ngtemplates
...
Reading <my templates>...OK
Writing template.js...ERROR
Warning: Unable to write "template.js" file (Error code: undefined). Use --force to continue.

Aborted due to warnings.

this is an unhelpful error emitted from grunt's file.write function (which you us) and after some digging I realized that the real error was "TypeError: path must be a string" and that clued me into my mistake.

I might have expected an error message pointing out that dest had to be a string. Further the fact that it says:

Writing template.js

vs

Writing [ 'template.js' ]

Allowed me to think I was providing good data. (this is from this line from grunt.file.write)

grunt.verbose.write((nowrite ? 'Not actually writing ' : 'Writing ') + filepath + '...');

This is on version 0.5.1

edit: pointing out another thing where grunt's logging steered me wrong

usemin option doesn't work

Hi,
trying to append templates to final script file via usemin option but it doesn't work:

(I'm using Yeoman)

Here is HTML snippet

        <!-- build:js({.tmp,app}) scripts/scripts.js -->
        <script src="scripts/app.js"></script>
        <script src="scripts/controllers/main.js"></script>
        <!-- endbuild -->

Gruntfile:

  // compiles templates to cache
      ngtemplates: {
          dist: {
              options: {
                  module: 'testApp',
                  usemin: 'scripts/scripts.js'
              },
              cwd: '<%= yeoman.app %>',
              src: 'views/**/*.html',
              dest: '<%= yeoman.app %>/scripts/templates.js'
          }
      }
...
...
// build task
grunt.registerTask('build', [
    'clean:dist',
    'bower-install',
    'useminPrepare',
    'ngtemplates',
    'concurrent:dist',
    'autoprefixer',
    'concat',
    'ngmin',
    'copy:dist',
    'cdnify',
    'cssmin',
    'uglify',
    'rev',
    'usemin',
    'htmlmin'
  ]);

when running task:

$ grunt build

grunt throws this error:

Running "ngtemplates:dist" (ngtemplates) task
File dist/scripts/templates.js created.
>> Could not find usemin.generated path matching: scripts/scripts.js

Remove module name from template path

I want to create template .js file that has same path as .html.

I have standard yo angular structure of project

So I have in my directive (it's located in app/scripts/directives):

templateUrl : 'views/directives/menu.tpl'

My template is in app/views/directive/menu.tpl

When I run ngtemplates it generates following part of code:

angular.module("MyModule").run(["$templateCache",function(a){a.put("app/views/directives/menu.tpl"

you can see that it searches directive template in different place than it's defined in directive.js making it not found.

app/ should be removed from template path...

base option gone?

It looks like the base option got dropped in the rewrite. Is there another way of doing this, or does it just need to be reimplemented?

concat option with grunt-usemin v2.0

In grunt-usemin v2.0 branch: https://github.com/yeoman/grunt-usemin/tree/v2.0, the concat target is now unified to a single one called generated:

concat:
  { generated: 
   { files: 
      [ { dest: '.tmp/concat/styles/main.css',
          src: 
           [ 'app/components/normalize-css/normalize.css',
             '.tmp/styles/main.css' ] },
        { dest: '.tmp/concat/scripts/app.js',
          src: 
           [ 'app/scripts/app.js',
             'app/scripts/config/config.js' ] } ] } }

this makes both main.css and app.js in the example above contain the template script's content, is there a way to get around this problem?

Update plugin to work with Grunt 0.4.0

Consider making a separate branch and update the plugin to work with grunt 0.4.0.

This could be done on a separate branch.

Right now when running the task in grunt 0.4.0rc7, I get the following error:

Warning: Object #<Object> has no method 'expandDirs' Use --force to continue.

Script hangs? New to grunt

Not sure if this is an issue with the library (I assume it isn't), but maybe it will still help someone down the line. I installed the plugin, and I run grunt myawesomecompiletask and this is the output I get:

....all the setup and then
Running "ngtemplates:app" (ngtemplates) task
Verifying property ngtemplates.app exists in config...OK
Files: partials/angular_ui_modal_lightbox_carousel.html, partials/siteexplorer_container_partial.html, partials/siteexplorer_featuredsites_list.html, partials/siteexplorer_sites_detail.html, partials/siteexplorer_sites_habitat_list.html, partials/siteexplorer_sites_list.html, partials/ym_photo_gallery.html, partials/ym_site_badges_list.html -> dist/siteexplorer.templates.js
Options: angular="angular", bootstrap=undefined, concat=null, htmlmin={}, module="app", source=undefined, standalone=false, url=undefined
Reading partials/angular_ui_modal_lightbox_carousel.html...OK
Reading partials/siteexplorer_container_partial.html...OK
Reading partials/siteexplorer_featuredsites_list.html...OK
Reading partials/siteexplorer_sites_detail.html...OK
Reading partials/siteexplorer_sites_habitat_list.html...OK
Reading partials/siteexplorer_sites_list.html...OK
Reading partials/ym_photo_gallery.html...OK
Reading partials/ym_site_badges_list.html...OK

and then the script just hangs. For at least 5 minutes, I've tried several times, it never seems to complete :'(

Fully custom root path can not be defined

In my dev environment my views live at: app/views/*.html

My final compiled application expects the view ids to be '/views/*.html'

My config attempt here:

ngtmplates:
    dist:
        options:
            base: 'views/'
        src: ['app/views/**.html']
        dest: '.tmp/js/views.js'

I expect base to over-write the base-url of the generated ids so they are '/views/somefile.html' however it produces '../app/views/somefile.html' instead.

Any ideas of an option combination to deal with this case, or perhaps make a blanket way to hard-code my preferred full-path to the filenames in the ids?

concat not working in Windows?

Seems like the concat option isn't working in Windows, when used with usemin, due to path issues. Same gruntfile works on osx/linux.

error

prefix '/'

Ok, I just spent a good 10 hours trying to find a bug with my templates. Turned out that my use of templates was like this: '/somewhere/file.html', and ngTemplates was generating 'somewhere/file.html' as the template key.

Now I'm not trying to argue what is the correct way of writing URI's or anything, but surely there is a way to stop someone else in the future arriving at the same problem?

Too Awesome

This project is too awesome. That is all.

Template named "undefined.html" is ignored

For various reasons we use a template named "undefined.html" in our current project.
But it seems it's being ignored by the compiler. All our other templates work perfectly.

module option

What about this idea: instead of creating app.templates module, just let people specify the name of the module to add templates to:

ngtemplates: {
      app: {
        src: ['app/templates/**/*.html'],
        dest: 'app/templates.js',
        module: 'app'
      }
    },

That way you wouldn't have to specify a dependency:

angular.module('app', []);

The benefit of this is you don't have to run a build before being able to use your app.

Example configuration for latest Grunt 0.4.4 is missing

I would like to append all cached templates to e.g dist/scripts/vendor.js

concat: {
  app: {
    src: ['**.js', '<%= ngtemplates.app.dest %>'],
    dest: ['<%= yeoman.dist %>/scripts/vendor.js']
  }
},

ngtemplates: {
  app: {
    src: 'app/views/**/*.html',
    dest: 'vendor.js'
  }
 },

Just append not override - as I want to decrease the number of HTTP request, what is the proper configuration to do that?

Some verbose output from grunt build

Running "concat:app" (concat) task
Verifying property concat.app exists in config...OK
Files: Gruntfile.js, karma-e2e.conf.js, karma.conf.js -> dist/scripts/vendor.js
Options: separator="\n", banner="", footer="", stripBanners=false, process=false
Reading Gruntfile.js...OK
Reading karma-e2e.conf.js...OK
Reading karma.conf.js...OK
Writing dist/scripts/vendor.js...ERROR
Warning: Unable to write "dist/scripts/vendor.js" file (Error code: undefined). Use --force to continue.

Tools and versions

grunt-cli v0.1.13
grunt v0.4.4
ngtemplates v0.5.4

HTMLmin is not fully compatible with Angular

Hi

I'm just letting you know that html-minifier (https://github.com/kangax/html-minifier/), which is used by grunt-usemin is not fully compatible with AngularJS.

AngularJS has support for inline JSON, but html-minifier actually escapes inline JSON.
Please see Issue 98 for more information on this.
(kangax/html-minifier#98 (comment))

A way to work around this is simply by not using the htmlmin option in the ngTemplates grunt task. As of now, there is no option to configure this.

You might want to document this behaviour. :)

Fix newlines in templateCache

On Windows the templateCache is generated with \r\n, on Mac it is only \n.

Can this be fixed with some configuration option?

As a Mac user I'm working on a project with a Windows user, and we're switching every time.

minify html

I was wondering if there is an easy way to minify the angular html templates? I tried running grunt-contrib-htmlmin and it concatenates all the angular templates into a single file, which breaks everything.

Fails to combine multiple templates

Noted in ericclemmons/genesis-skeleton/#20, when multiple templates need to be combined, only the last one (or the first?) is present. The rest are missing.

Wrong parsing when using < inside text

This code comes directly from angular-ui bootstrap template:

<span ng-mouseleave="reset()" ng-keydown="onKeydown($event)" tabindex="0" role="slider" aria-valuemin="0" aria-valuemax="{{range.length}}" aria-valuenow="{{value}}">
    <i ng-repeat="r in range track by $index" ng-mouseenter="enter($index + 1)" ng-click="rate($index + 1)" class="glyphicon" ng-class="$index < value && (r.stateOn || 'glyphicon-star') || (r.stateOff || 'glyphicon-star-empty')">
        <span class="sr-only">({{ $index < value ? '*' : ' ' }})</span>
    </i>
</span>

and the plugin fails on

<span class="sr-only">({{ $index < value ? '*' : ' ' }})</span>

I temporary changed it to an ng-bind-template, are there any chance you update the plugin to fix it?

path adding a ./ prefix

Looks like the new version is appending a "./" to the paths i generate now. I've moved back to the previous version and it went away. Tried adding a prefix but it didn't seem to help:

ngtemplates:
myApp:
cwd: "./client"
src: "./views/*/.html"
dest:"./public/js/templates.js"
prefix: ""

Module Compatibility

I've just done a pull request (#29) in order to make the plugin more customizable. This is because I work with lazy modules and I need a different structure.

Due to this, I need to compile the templates by module, rather than by project. However I think this isn't easy to do with the current version. I achieved this creating a task for each module, but it's very painful because make me duplicate configuration code in the Gruntfile.

A way to compile templates by module/folder would be excellent

BTW, if anybody knows a better way to do this with the current version, reply please! :)

options.source usage?

I've been trying to use the source callback as a means to handle haml templates by wrapping the haml grunt task..... but w/o much success.

Any chance you can post an example of using the source callback?

(As a side note, I ended up just including a haml step in the grunt build before the ngtemplates, and configuring ngtemplates a source that picks them both:

  src: ["app/templates/**/*.html", 'generated/app/templates/**/*.html'],

)

Error with latest Node: Arguments to path.resolve must be strings Use --force to continue.

Looks like there was some change to Path.

Only occurs when options.base is undefined.

TypeError: Arguments to path.resolve must be strings
at Object.exports.resolve (path.js:313:15)
at Object.exports.relative (path.js:370:20)
at /home/bpippin/Texeltek/ircop-ui/node_modules/grunt-angular-templates/tasks/lib/compiler.js:17:54
at /home/bpippin/Texeltek/ircop-ui/node_modules/grunt/node_modules/async/lib/async.js:541:13
at iterate (/home/bpippin/Texeltek/ircop-ui/node_modules/grunt/node_modules/async/lib/async.js:108:13)
at async.forEachSeries (/home/bpippin/Texeltek/ircop-ui/node_modules/grunt/node_modules/async/lib/async.js:124:9)
at _concat (/home/bpippin/Texeltek/ircop-ui/node_modules/grunt/node_modules/async/lib/async.js:540:9)
at Object.concatSeries (/home/bpippin/Texeltek/ircop-ui/node_modules/grunt/node_modules/async/lib/async.js:174:23)
at concat (/home/bpippin/Texeltek/ircop-ui/node_modules/grunt-angular-templates/tasks/lib/compiler.js:16:22)
at Object.compile (/home/bpippin/Texeltek/ircop-ui/node_modules/grunt-angular-templates/tasks/lib/compiler.js:29:5)

Empty templates are incorrectly transformed

I use grunt-angular-templates 0.4.0. I've just discovered it incorrectly transforms empty templates, it results in:

  $templateCache.put('/templates/item-row.html',

  );

which is a syntax error. It should put an empty string under this ID instead.

Regression in quoting breaks with Angular v1.2.0-rc.2

There was a regression between grunt-angular-templates version 0.3.10 and the latest 0.4.1.

Previously, it would generate code like the following:

angular.module("module-name").run(["$templateCache", ...
$templateCache.put("/public/html/templateName.html",

but now it generates:

angular.module('module-name').run(['$templateCache', ...
$templateCache.put('/public/html/templateName.html',

In addition, it appears to be making the templates XHTML; for example it converts stand-alone <img> tags into self-closing <img /> tags, and standalone directives like <div myDirective> into <div myDirective=\"\">.

I'm not sure exactly why, but these changes to the generated templates is causing Angular v1.2.0-rc.2 to no longer recognize them, and thus Angular tries to use XHRs to fetch the templates manually.

How to change default 'app'?

My main module is not called 'app'. When I run it I get "can't find variable app" furthermore, if I hand tweak it to be 'MyShortlyNamedApplicationModule' by hand, it still says it can't find it.

Any advice?

Extend tests

Hello everyone,

This package is great and works fine on my end.
Is there a plan to add tests for invalid templates (missing closing tags, malformed urls, etc.) and edge cases?

If yes, the package could then be used as part of the yeoman angularjs generator build process. (see yeoman/generator-angular#277 (comment) )

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.