GithubHelp home page GithubHelp logo

miickel / gulp-angular-templatecache Goto Github PK

View Code? Open in Web Editor NEW
524.0 10.0 103.0 163 KB

Concatenates and registers AngularJS templates in the $templateCache.

License: MIT License

JavaScript 100.00%
templatecache angularjs javascript gulp gulp-plugin

gulp-angular-templatecache's Introduction

gulp-angular-templatecache

The npm package related to this repo was deprecated after v3.0.1 was published on 02/17/22. Ownership has been responsibly transferred to npm.


License NPM version NPM version Build Status Dependency Status

Concatenates and registers AngularJS templates in the $templateCache.

Install | Example | API | Releases | License


Install

Install with npm

npm install gulp-angular-templatecache --save-dev

Example

gulpfile.js

Concatenate the contents of all .html-files in the templates directory and save to public/templates.js (default filename).

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

gulp.task('default', function () {
  return gulp.src('templates/**/*.html')
    .pipe(templateCache())
    .pipe(gulp.dest('public'));
});

Result (public/templates.js)

Sample output (prettified).

angular.module("templates").run([$templateCache,
  function($templateCache) {
    $templateCache.put("template1.html",
      // template1.html content (escaped)
    );
    $templateCache.put("template2.html",
      // template2.html content (escaped)
    );
    // etc.
  }
]);

Include this file in your app and AngularJS will use the $templateCache when available.

Note: this plugin will not create a new AngularJS module by default, but use a module called templates. If you would like to create a new module, set options.standalone to true.

Note: if you use Visual Studio on Windows, you might encounter this error message: ASPNETCOMPILER : error ASPRUNTIME: The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters.

This is most likely due to long path names, and can be fixed by adding lodash.bind as a dev dependecy in your package.json. Anyway, if you encounter this error, please drop a note in #62, and we might merge #63.

API

gulp-angular-templatecache(filename, options)


filename - {string} [filename='templates.js']

Name to use when concatenating.

options

root - {string}

Prefix for template URLs.

module - {string} [module='templates']

Name of AngularJS module.

standalone - {boolean} [standalone=false]

Create a new AngularJS module, instead of using an existing.

base {string | function} [base=file.base]

Override file base path.

moduleSystem {string}

Wrap the templateCache in a module system. Currently supported systems: RequireJS, Browserify, ES6 and IIFE (Immediately-Invoked Function Expression).

transformUrl {function}

Transform the generated URL before it's put into $templateCache.

transformUrl: function(url) {
	return url.replace(/\.tpl\.html$/, '.html')
}

templateHeader {string} [templateHeader=see below]

Override template header.

var TEMPLATE_HEADER = 'angular.module("<%= module %>"<%= standalone %>).run(["$templateCache", function($templateCache) {';

templateBody {string} [templateBody=see below]

Override template body.

var TEMPLATE_BODY = '$templateCache.put("<%= url %>","<%= contents %>");';

templateFooter {string} [templateFooter=see below]

Override template footer.

var TEMPLATE_FOOTER = '}]);';

escapeOptions - {object}

Options for jsesc module. See jsesc API

Changes

This plugin uses Semantic Versioning 2.0.0

1.1.0 and newer

See Releases

1.0.0

Cleaner code, more tests and improved documentation. Thoroughly used in development.

  • adds
    • options.standalone (breaking)
  • fixes
    • Windows support
  • changes
    • filename now optional

0.3.0

  • adds
    • options.module

0.2.0 and earlier

Only used by mad men

License

The MIT License (MIT)

Copyright (c) 2014 Mickel

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Analytics

gulp-angular-templatecache's People

Contributors

aeharding avatar basa0 avatar clkao avatar demurgos avatar dmellstrom avatar greg-nagy avatar jakooob avatar johnhok avatar karlhorky avatar kimjoar avatar kityan avatar merott avatar miickel avatar pheuter avatar prajwalkman avatar sahat avatar scottrain avatar simonua avatar tandrewnichols avatar the-ress avatar tomsoal avatar willpracht 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

gulp-angular-templatecache's Issues

Modifying the path

Currently, any path that contains .. or . will be rewritten to omit those because path.join() and path.normalize() do this.

This is inconvenient when using RequireJS's require.toUrl() as it will prepend ./ to the generated URLs (since require has to know where the file is). These are effectively the keys that are then used to look up the appropriate template by angular, hence the need to keep this path the way it is.

Do you have any suggestions for how to handle this? I have attempted using both the base and root options, but both of these get normalized.

If I were to submit a PR for this, I would probably add a hook to modify the url one last time before it is actually added to the template file, thereby avoiding the whole normalization problem. But I am not sure whether or not this is the path you'd like to take.

New gulp-header version introduces an error

The new 1.5.0 release of gulp-header introduced an issue. Because of this issue, gulp-angular-templatecache is now no longer working.

This is mostly gulp-header's problem, but maybe you can update your dependency versions to only auto-update patches.

"gulp-header": "~1.4.0" instead of "gulp-header": "1.x" would have prevented this issue.

Can you tighten your dependency versions so these bugs can be prevented in the future?

$injector:modulerr when including ['templates']

I followed the documentation to include templates.js in my app module:

angular.module('MyApp', ['ngRoute', 'ngAnimate', 'ngProgress', 'ngDisqus', 'ngTable', 'templates'])

templates.js

angular.module("MyApp", []).run(["$templateCache", function($templateCache) {$templateCache.put("views/404.html","<link href=\'http://fonts.googleapis.com/css?family=Monoton\' rel=\'stylesheet\'\n      type=\'text/css\'>\n<style>\n  body {\n    background: #3D4452;\n  }\n\n  .error {\n    position: absolute;\n    top: 50%;\n    left: 50%;\n    height: 150px;\n    width: 500px;\n    margin: -175px 0 0 -250px;\n    padding: 20px;\n    font-size: 75px;\n    font-family: \'Monoton\', cursive;\n    text-align: center;\n    text-transform: uppercase;\n    color: #e4545b;\n  }\n\n  .error p {\n    margin: 0;\n    text-shadow: 0 0 180px #e4545b, 0 0 70px #ff003e, 0 0 12px #ff3223;\n\n  }\n\n  #error {\n    color: #fff;\n    text-shadow: 0 0 200px #812eff, 0 0 80px #9982d8, 0 0 10px #bb4eff;\n  }\n</style>\n\n<div class=\"error\">\n  <p id=\"error\">E<span>r</span>ror</p>\n\n  <p id=\"code\">4<span>0</span><span>4</span></p>\n</div>");
$templateCache.put("views/contribute.html","<div class=\"container\">\n  <h3>Contributing Guidelines</h3>\n\n  <p>\n    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer leo est,\n    tincidunt placerat elit eu, feugiat rhoncus odio. Maecenas augue sem,\n    eleifend\n    et sapien sodales, semper mattis odio. Interdum et malesuada fames ac ante\n    ipsum primis in faucibus. Ut vestibulum nisi tincidunt, elementum quam nec,\n    dapibus eros. Quisque at augue sed dui fringilla tempus imperdiet eu nulla.\n    Etiam euismod est augue, laoreet eleifend lorem consequat porta. Proin\n    blandit\n    ante volutpat augue adipiscing, id convallis sem vulputate. Nullam et congue\n    sapien, nec euismod purus. Etiam suscipit eleifend libero, quis tempus lorem\n    viverra nec. Suspendisse ultrices nisi eu erat tristique, sed interdum lorem\n    rutrum. Nulla dapibus, eros vel iaculis rhoncus, quam risus elementum magna,\n    ac tincidunt metus nunc ac lorem. Donec placerat tristique ipsum. Vestibulum\n    hendrerit tristique nisl, eget pulvinar magna aliquam ut. Nam vulputate\n    augue\n    sem, eget feugiat mauris molestie at. Aliquam erat volutpat.\n  </p>\n\n  <h3>Top Contributors</h3>\n  <table class=\"table\">\n    <tr ng-repeat=\"user in contributors\">\n      <td class=\"col-xs-1\"><img src=\"{{ user.avatar_url }}\"></td>\n      <td><a href=\"{{ user.html_url }}\">{{ user.login }}</a></td>\n      <td>{{ user.contributions }} commits</td>\n    </tr>\n  </table>\n</div>");
$templateCache.put("views/detail.html","<div class=\"jumbotron\">\n    <h1>{{ post.title }}</h1>\n  <p>{{ post.description }}</p>\n</div>\n\n<div class=\"container\">\n  <div scroll markdown file=\"{{ post.file }}\"></div>\n\n\n  <i class=\"text-muted\">Last updated {{ lastUpdated }}</i>\n\n  <div disqus=\"post.file\"></div>\n</div>\n\n<a href=\"https://github.com/sahat/fullstack/edit/gh-pages/posts/{{ post.file }}\"\n   class=\"edit-on-github\"><i class=\"fa fa-file-text-o\"></i> Improve this doc</a>\n");
$templateCache.put("views/feedback.html","<div class=\"container\">\n  <br/>\n\n  <p><i class=\"fa fa-comments\"></i> If you have comments and/or suggestions, send me a message at\n    <a href=\"mailto:[email protected]\">[email protected]</a>.</p>\n  <hr/>\n  <p>For questions regarding a particular post,\n    plese open a new <a href=\"https://github.com/sahat/jsrecipes/issues\">GitHub Issue</a>.</p>\n</div>");
$templateCache.put("views/main.html","<div class=\"jumbotron\">\n  <h1>JS Recipes {{ title }}</h1>\n\n  <p>Description placeholder, update later with a more meaningful website\n    description.</p>\n</div>\n<div class=\"social-bar\">\n  <div class=\"container\">\n    <!--GitHub Star Button-->\n    <iframe\n      src=\"http://ghbtns.com/github-btn.html?user=sahat&repo=jsrecipes&type=watch&count=true\"\n      allowtransparency=\"true\" frameborder=\"0\" scrolling=\"0\" width=\"107\"\n      height=\"20\"></iframe>\n\n    <!--Facebook Like Button-->\n    <iframe\n      src=\"//www.facebook.com/plugins/like.php?href=http%3A%2F%2Fjsrecipes.org&amp;width&amp;layout=button_count&amp;action=like&amp;show_faces=false&amp;share=false&amp;height=21&amp;appId=621491837925521\"\n      scrolling=\"no\" frameborder=\"0\"\n      style=\"border:none; overflow:hidden; width:107px; height:21px;\"\n      allowTransparency=\"true\"></iframe>\n\n    <!--Twitter Share Button-->\n    <a href=\"https://twitter.com/share\" class=\"twitter-share-button\" data-url=\"http://jsrecipes.org\" data-via=\"EvNowAndForever\">Tweet</a>\n    <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?\'http\':\'https\';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+\'://platform.twitter.com/widgets.js\';fjs.parentNode.insertBefore(js,fjs);}}(document, \'script\', \'twitter-wjs\');</script>\n\n    <!--Google +1 Button-->\n    <script type=\"text/javascript\" src=\"https://apis.google.com/js/platform.js\"></script>\n    <div class=\"g-plusone\" data-size=\"medium\" data-href=\"http://jsrecipes.org\"></div>\n  </div>\n</div>\n\n<div class=\"container\">\n\n  <h2><i class=\"fa fa-hdd-o\"></i> Backend</h2>\n  <hr/>\n\n  <div class=\"panel panel-success\">\n    <div class=\"panel-heading\">\n      <h3 class=\"panel-title\">Beginner</h3>\n    </div>\n    <div class=\"list-group\"\n         ng-repeat=\"post in posts.backend.beginner | orderBy:\'title\'\">\n      <a href=\"#!/backend/{{ post.slug }}\" class=\"list-group-item\">{{ post.title\n        }}</a>\n    </div>\n  </div>\n\n  <div class=\"panel panel-warning\">\n    <div class=\"panel-heading\">\n      <h3 class=\"panel-title\">Intermediate</h3>\n    </div>\n    <div class=\"list-group\"\n         ng-repeat=\"post in posts.backend.intermediate | orderBy:\'title\'\">\n      <a href=\"#!/backend/{{ post.slug }}\" class=\"list-group-item\">{{ post.title\n        }}</a>\n    </div>\n  </div>\n\n  <div class=\"panel panel-danger\">\n    <div class=\"panel-heading\">\n      <h3 class=\"panel-title\">Advanced</h3>\n    </div>\n    <div class=\"list-group\"\n         ng-repeat=\"post in posts.backend.advanced | orderBy:\'title\'\">\n      <a href=\"#!/backend/{{ post.slug }}\" class=\"list-group-item\">{{ post.title\n        }}</a>\n    </div>\n  </div>\n\n  <h2><i class=\"fa fa-html5\"></i> Frontend</h2>\n  <hr/>\n\n  <div class=\"panel panel-success\">\n    <div class=\"panel-heading\">\n      <h3 class=\"panel-title\">Beginner</h3>\n    </div>\n    <div class=\"list-group\"\n         ng-repeat=\"post in posts.frontend.beginner | orderBy:\'title\'\">\n      <a href=\"#!/frontend/{{ post.slug }}\" class=\"list-group-item\">{{\n        post.title }}</a>\n    </div>\n  </div>\n\n  <div class=\"panel panel-warning\">\n    <div class=\"panel-heading\">\n      <h3 class=\"panel-title\">Intermediate</h3>\n    </div>\n    <div class=\"list-group\"\n         ng-repeat=\"post in posts.frontend.intermediate | orderBy:\'title\'\">\n      <a href=\"#!/frontend/{{ post.slug }}\" class=\"list-group-item\">{{\n        post.title }}</a>\n    </div>\n  </div>\n\n  <div class=\"panel panel-danger\">\n    <div class=\"panel-heading\">\n      <h3 class=\"panel-title\">Advanced</h3>\n    </div>\n    <div class=\"list-group\"\n         ng-repeat=\"post in posts.frontend.advanced | orderBy:\'title\'\">\n      <a href=\"#!/frontend/{{ post.slug }}\" class=\"list-group-item\">{{\n        post.title }}</a>\n    </div>\n  </div>\n\n  <h2><i class=\"fa fa-star\"></i> General</h2>\n  <hr/>\n\n  <div class=\"panel panel-primary\">\n    <div class=\"panel-heading\">\n      <h3 class=\"panel-title\">Best Practices</h3>\n    </div>\n    <div class=\"list-group\" ng-repeat=\"post in posts.general | orderBy:\'title\'\">\n      <a href=\"#!/general/{{ post.slug }}\" class=\"list-group-item\">{{ post.title\n        }}</a>\n    </div>\n  </div>\n\n</div>\n\n\n");}]);

I tried including it manually by placing it inside .run, it works, so there is nothing wrong with the templates.js.

I am getting this error which is probably because I am doing something wrong with Angular module system:

Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.3.0-beta.5/$injector/modulerr?p0=MyApp&p1=Err…ularjs.org%2F1.3.0-beta.5%2F%24injector%2Fmodulerr%3Fp0%3Dtemplates%26p1%3...<omitted>...4) 

Gulp Task

gulp.task('templates', function () {
  gulp.src('views/**/*.html')
    .pipe(templateCache({ root: 'views', module: 'MyApp' }))
    .pipe(gulp.dest('scripts'));
});

perhaps you move the filename specification into option?

it strange that if i want to specify some option that i should specify the filename first which i want to use the default~~. i think it's better that specify the filename in the option object if you need. it's more convenient and clean!

[Suggestion] Strip HTML comments

It seems that HTML comments are retained. I can see why some people would wish to have these retained for Angular purposes. However for those of us who don't use HTML comments for anything but commenting, it would be nice to have these stripped out to minimise the output.

Thanks

Problem minifying using gulp with ui-router?

Hi,

When using a .config in ui-router such as

.config(['$stateProvider','$urlRouterProvider','$locationProvider',function ($stateProvider,$urlRouterProvider,$locationProvider) {
etc etc
}]);

and a route defintion whereby "templateUrl" is replaced by eg

templateProvider:function($templateCache) {
return $templateCache.get('home.html');
}

I can't minify the code using ugilify and concat.

I've tried injecting $templateCache as a dependency in .config() but of course that doesnt work .... any ideas what to do to get this to work?

Problem with gulp.src base option

Given the following:

gulp.src(["src/**/*.html", "!src/index.html"], {base: "src"})
    .pipe(gulpif(condition, templateCache()))
        ...
    .pipe(gulp.dest("build"));

I end up with files like /Users/lukescott/Documents/Projects/app/view/view.html. Even though this appears to be a full path, this is wrong anyway. There is no "src" folder or "build" folder in this path. If I remove the base option it works fine. The problem is here:

https://github.com/miickel/gulp-angular-templatecache/blob/v1.4.0/index.js#L49

What's happening is it's simply replacing "src" with nothing. The correct approach, from what I can tell, is do something like this instead:

switch(typeof base) {
case 'function':
    url = path.join(root, base(file));
    break;
case 'string': // default?
    url = path.join(root, file.path.replace(base || file.base, ''));
case 'undefined':
    url = path.join(root, file.relative); // Should fix above case
default:
    // unknown type?
}

It seems that the string case could still be wrong because it's supposed to replace from the left side, not the middle, correct?

The workaround I have for now is this:

gulp.src(["src/**/*.html", "!src/index.html"], {base: "src"})
    .pipe(gulpif(condition, templateCache({base: function(file) {
            return file.relative;
        }})))
        ...
    .pipe(gulp.dest("build"));

Child module templateCache

This is more of a question than an issue, but I was wondering how I can get this to work with child modules.

Most of my templates are referenced as follows via ui-router, and everything works as expected:

var app = angular.module('app', [
    'app.filters',
    'app.services',
    'app.controllers',
    'app.directives',
    'ngSanitize',
    'ngResource'
  ])
  .config(['$stateProvider', '$urlRouterProvider',
    function($stateProvider, $urlRouterProvider) {
      $stateProvider
        .state('page1', {
          url: '/page1',
          templateUrl: 'partials/page1.html'
         })

        .state('page2', {
          url: '/page2',
          templateUrl: 'partials/page2.html'
        })
    ...
  });

However, as you can see in the dependencies I inject above, I also have this:

angular.module('app.directives', [])
.directive('collapsible', function() {
    return {
        scope: {
            title: '@'
        },
        restrict: 'E',
        replace: true,
        transclude: true,
        templateUrl: 'partials/directives/collapsible.html',
        controller: function($scope) {
            $scope.collapsed = false;
            $scope.collapse = function() {
                $scope.collapsed = !$scope.collapsed;
            };
        }
    };
});

When running my app, I get the error [$compile:tpload] and the GET request to partials/directives/collapsible.html returns a 404, since it doesn't exist, obviously, since I want to use the templateCache.

I know what I'm getting the error, I'm just wondering how I can make app.directives aware of the templateCache for app. Gulp code is as follows:

// prod or test: create $templateCache
    gulp.src('partials/**/*.html')
      .pipe(ngCache({
          filename: 'partials.js',
          module: 'app'
        }))
      .pipe(gulp.dest('www'))
    ;

htmlmin options

I have migrated from grunt to gulp on my project.
Though I was using grunt-angular-templates with htmlmin options, this gulp task has no the options.

Is it possible to add htmlmin option for this task ?

html

<div class="sample">
  <ul class="sample-list">
    <li>sample</li>
  </ul>
</div>

current output

angular.module("app.templates", []).run(["$templateCache", function($templateCache) {$templateCache.put("html/components/chat/stamp-carousel.html","<div class=\"sample\">\n  <!-- a sample list -->\n  <ul class=\"sample-list\">\n    <li>sample</li>\n  </ul>\n</div>\n");}]);

expect output with htmlmin options

  • remove comments
  • remove whitespace
  • remove line code
angular.module("app.templates", []).run(["$templateCache", function($templateCache) {$templateCache.put("html/components/chat/stamp-carousel.html","<div class=\"sample\"><ul class=\"sample-list\"><li>sample</li></ul></div>");}]);

on generation, second file's templateFooter becomes ".no"

We've got a really strange problem here, the angular.module ending of the second processed file is suddenly .no instead of );
Sometimes it works, but sometimes not. Cannot really reproduce it, seems more to be a bit of luck.

Outcome:

... <div data-ng-if=\"registerevent === \'success\'\" data-ng-include=\"\'public/js/app/account/templates/response.html\'\">\n    </div>\n  </article>\n</div>".no
$templateCache.put("public/js/app/account/templates/create-project.html","<div class=\"marketplace project\">\n    <article id=\"page\" class=\"page container-fluid\">\n        

Implementation

// Gulp task for creating template cache
gulp.task('html2js', function() {
    var config = {
        htmltemplates: bases.dev + paths.js + 'app/**/*.html',
        templateCache: {
            file: 'templates.js',
            options: {
                module: 'ds.templates',
                root: 'public/js/app/',
                standalone: true
            }
        }
    };
    return gulp
        .src(config.htmltemplates)
        .pipe(plumber({
            errorHandler: onError
        }))
        .pipe(templateCache(
            config.templateCache.file,
            config.templateCache.options
        ))
        .pipe(plumber.stop())
        .pipe(gulp.dest(bases.tmp));
});

Versions:
gulp-angular-templatecache: 1.6.0
gulp: 3.8.8
node: 0.12.0

Any ideas how to tackle that thing?

Regards, Markus

Error when using browserify moduleSystem

When doing this in my Gulpfile:

gulp.task('templates', function () {
    gulp.src('./views/**/*.html')
        .pipe(templateCache({moduleSystem: 'browserify'}))
        .pipe(gulp.dest('./'));
});

I get the following error:

/example/node_modules/gulp-angular-templatecache/node_modules/event-stream/node_modules/map-stream/index.js:103
        throw err
              ^
TypeError: Object.keys called on non-object
    at keys (native)
    at assign (eval at <anonymous> (/example/node_modules/es6ify/node_modules/traceur/src/node/traceur.js:24:17), <anonymous>:2308:19)
    at DestroyableTransform._transform (/example/node_modules/gulp-angular-templatecache/node_modules/gulp-header/index.js:13:51)
    at DestroyableTransform.Transform._read (/example/node_modules/gulp-angular-templatecache/node_modules/gulp-header/node_modules/through2/node_modules/readable-stream/lib/_stream_transform.js:184:10)
    at DestroyableTransform.Transform._write (/example/node_modules/gulp-angular-templatecache/node_modules/gulp-header/node_modules/through2/node_modules/readable-stream/lib/_stream_transform.js:172:12)
    at doWrite (/example/node_modules/gulp-angular-templatecache/node_modules/gulp-header/node_modules/through2/node_modules/readable-stream/lib/_stream_writable.js:237:10)
    at writeOrBuffer (/example/node_modules/gulp-angular-templatecache/node_modules/gulp-header/node_modules/through2/node_modules/readable-stream/lib/_stream_writable.js:227:5)
    at DestroyableTransform.Writable.write (/example/node_modules/gulp-angular-templatecache/node_modules/gulp-header/node_modules/through2/node_modules/readable-stream/lib/_stream_writable.js:194:11)
    at Stream.ondata (stream.js:51:26)
    at Stream.EventEmitter.emit (events.js:95:17)

Looks like gulp-header requires an options argument.

extension option

boolean (default true)

do not write ".html" extension everywhere could be nice.

Incorrect module definition for 'templates'

Hi,

Angular requires the following:

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

Currently, the task only does:

angular.module('templates');

this causes an error on the latest versions of angular. Please check.

lodash.bind, Windows and long paths

Hi @miickel,

First up - thanks for the plug-in!

I don't know if you're aware of this but gulp-angular-templatecache can upset Visual Studio on Windows. Once I installed it I started getting this message:

ASPNETCOMPILER : error ASPRUNTIME: The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters.

This seems to be related to the long path issues discussed here. The workaround seems to be adding lodash.bind as a dev dependency to packages.json. This way npm doesn't get the longer path underneath gulp-angular-templatecache in node_modules. Thought I'd share it here since it burned a good portion of my time and I wanted to save anyone else the frustration I'd dealt with.

Bad template id generated on Windows

Although I'm not a big fan on working in node.js on Windows, this still happens from time to time.

My gulp task is defined like this:

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

gulp.src(['app/**/*.jade', '!app/**/_*.jade'], {cwd: 'src', base: 'src'})
  .pipe(plugins.plumber())
  .pipe(plugins.jade({client: false, clientDebug: false, pretty: false}))
  .pipe(plugins.templateCache('app-templates.js', {module: 'pkgApp'}))
  .pipe(gulp.dest(buildConfig.outputPath));

and the output is:

angular.module("pkgApp")
    .run(["$templateCache", function($templateCache) {
        $templateCache.put("D:/projects/pkg/app/app.html","<div></div>");
    }]);

The bad thing here is the template id: "D:/projects/pkg/app/app.html"
Is there a way I can get around this issue without having to go through the source code?

Inconsistent line endings \n vs \r\n

Problem

I'm not sure if this is an oversight or an enhancement request.

Each time I run my gulp project it compiles my html files and puts it in the template cache for me. This works great! However, depending on the machine your template cache either has line endings as \r\n or \n. \r\n occurs on windows machines and \n occurs in linux/Mac machines. My template.js file is in version control so often the template.js file is checked in again even though there are no changes (besides line endings). Is there a way to normalize this so I only get line endings?

Proposed solution

Add a lineEndings setting, letting the user specify what it should always be. Maybe something like:

  return gulp.src(paths.templates)
    .pipe(addTemplates(paths.appName + '.templates.js', {
      module: paths.appName,
      lineEndings: '\n'
    }))
    .pipe(gulp.dest('js'));

Example

Example *.html files:

<p>Foo</p>
<p>bar</p>

Result on a windows machine:

angular.module("exampleApp").run(["$templateCache", function($templateCache) {$templateCache.put("example.html","<p>Foo</p>\r\n <p>Bar</p>");}]);

Result on Mac/Linux

angular.module("exampleApp").run(["$templateCache", function($templateCache) {$templateCache.put("example.html","<p>Foo</p>\n <p>Bar</p>");}]);

transformUrl not working?

Sorry to post such a simple question, but I want to make sure I'm writing my statement correctly. What I'm trying to do is append a timestamp to each .html file being put into the template cache, to try to cachebust it on the fly since our templateCache task is being watched for changes and recompiles as we edit HTML files.

This is how I'm approaching the statement (I'm using gulp-util so that's why the module name looks funny:

.pipe($.angularTemplatecache('templates.js', { transformUrl: function (url) { return url + '?' + date.toJSON(); } }))

Along with the full task:

gulp.task('template', function() {

    var date = new Date();
    return gulp.src(config.dir.ngDev + '**/*.html')
        .pipe($.plumber({ errorHandler: onError }))
        .pipe($.angularTemplatecache('templates.js', { transformUrl: function (url) { return url + '?' + date.toJSON(); } }))
        .pipe(gulp.dest(dest.ngCompiled));

});

Example outputs nothing

gulp.task('default', function () {
    return gulp.src('templates/**/*.html')
        .pipe(templateCache())
        .pipe(gulp.dest('public'));
});


Doesn't out put anything

angular.module("templates") fails

The output currently starts like this:

angular.module("templates").run(

With angular 1.2.26, this does not work for me -- it complains that the dependencies argument must be provided. I'm working around this by using gulp-replace to inject an empty list for the dependencies so the output then starts like this:

angular.module("templates",[]).run(

api doesn't work

templateHeader doesn't work
templateFooter doesn't work
base doesn't work (use path.resolve instead of file.path.replace)
moduleSystem doesn't work (with custom dependencies)

Issue while creating or parsing html

Some of templates are missing the quotes for html element attributes like

Original html (part of it)

<a class="non-expanding-text" editable-text="team.name" blur="submit" e-placeholder=""></a>

the templates contains

$templateCache.put("<a class=non-expanding-text editable-text=team.name blur=submit e-placeholder></a>");

Angular 1.4 new router support

Hello, I have configured my templateCache function to dasherize my paths in the template cache (based on @Foxandxss angular boilerplate)

function buildTemplates() {
  return es.pipeline(
    plugins.minifyHtml({
      empty: true,
      spare: true,
      quotes: true
    }),
    plugins.angularTemplatecache({
      module: 'wokapp',
      root:'./components'
    })
  );
}

But when the cache file is built, the dasherized path is removed:

$templateCache.put("components/users/user.html","<div>User</div>");

No HTML files

If a use gulp.src('src/*/.html')... with this tool and there are no html files, the tool breaks. Could you upgrade to gracefully handle the case when no files are passed to the tool.

Thanks!

Issues when files are coming from gulp-remember

gulp-remember is useful if the templates are preprocessed by e.g jade.

As gulp-angular-templatecache is a process + concat, plugin, this gives issues.

gulp-remember caches the whole file object, but templateCache is overwritting the contents of that object.
When the stream re-runs without change to some files, the Buffer output by templateCache is resent as Input, which is not what we want.

Angular requires error / injection error

Hi there!

I'm using angular v1.4.0-beta.6 and running into this error:

Uncaught Error: [$injector:nomod] Module 'templates' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.

So your plugin misses an empty array for the module registration:

angular.module("templates") => angular.module("templates". []).run([...]);

When I add an empty array manually it works and angular fetches the html templates as planned.

Is this an angular beta bug? Is it possible for you to fix this without screwing something else up? => I don't know the earlier module registration process by angular :).

Thanks in advance!

lost path. after templatecache

I try to create multiple template.js, but it lost dirname.

Can preserve dirname?

gulp.src( ['test/a//**/*.html','test/b/**/*.html' , {base: '.test' })
        .pipe(rename(function (path) {
            console.log(path);
            // print
            // { dirname: 'a', basename: 'hello', extname: '.html' }
            // { dirname: 'b', basename: 'hello', extname: '.html' }
        }))
        .pipe(templateCache({
            standalone: true
        }))
        .pipe(rename(function (path) {
            console.log(path);
            // print, lost 'dirname'
            // { dirname: '.', basename: 'templates', extname: '.js' }
        }))
        .pipe(gulp.dest(config.views.dest));

Option to select quote (single vs double)

Hi, first let me say it's a great package, it is working very well in here.

As a suggestion for a new feature I would say you could give, as an options, a chance to select which quote you will use to pack template content as string. Usually HTML has lots of " and you have to escape each of them. In my case I count more then 2k lost in \ for escaping only. If you use a single quote to define the string we can afford almost all (you still have to escape single quote, but it is not so common as double), of these escaping, right? or am I missing something?

Continuous compilation of template file

It would be fantastic if this plugin support functionality similar to gulp-continuous-concat. I would like to be able to update the template cache file piecemeal, so that compilation remains fast even when there are many, large templates to be compiled. Even if my template files are few and small, I would need this plugin to support this continuous concatenation functionality in order to be able to compile my JavaScript piecemeal without having to write the templates.js file out to disk.

issue with gulp-watch

Have you had any success using this with gulp-watch? I've already had it working with gulp.watch, but was hoping to get some of the extra features that gulp-watch provides

gulp.task('templatify', function() {
    return gulp.src('src/modules/**/*.html')
        .pipe(watch('src/modules/**/*.html'))
        .pipe(plumber())
        .pipe(template({moduleSystem: 'Browserify', module: 'sampleApp.templates' }))
        .pipe(gulp.dest('www/templates'));
});

Option to alias urls

It's possible for a programmer to accidentally specify an absolute path when he intends to specify a relative path:

templateUrl: '/common/foo/foo-directive.html'

vs

templateUrl: 'common/foo/foo-directive.html'

On a local development server, he might accidentally be able to resolve that url via angular's default behavior of sending an HTTP request there, but on production that path might not exist anymore. This can lead to hard-to-debug errors.

Ideally we'd always specify relative paths, but programmers make mistakes. So, I'd like an option to alias urls, such that the generated templateCache code for that url would be:

["common/foo/foo-directive.html","/common/foo/foo-directive.html"].forEach(function(u){$templateCache.put(u,"<div class=\"foo\"></div>")})

Alphabetical Order

Optionally make the output files output in alphabetical order. I know this sounds odd, but when using version control it will determine things have changed due to the order changing.

Here is an example of the problem
image

Way to build without templates.js file?

So I'm using angular + browserify and ideally this templates.js file would be completely transparent (meaning it only shows up in the browserify bundled js output). The reason I say that would be ideal, is because it is essentially a build artifact, and thus should not be versioned.

What I would like to do is append the contents to the browserify entry file prior to bundling, but I'm new to all this and can't figure out whether that's even possible.

I would appreciate your thoughts on how to accomplish this if it is possible.

Thanks,
Phil

Bug in `file.path`/`file.base` in windows

In windows, the drive letter capitalizations for file.path and file.base are different.

I printed from console and this is what I got:

file.path: D:\Project....
file.base: d:\Project....

As a result my templatecaches have wrong paths since the base never got removed. I'm not entirely familiar with how gulp works internally, so I'm not sure if this is a gulp issue or a nodejs core issue.

HTML Special Character encoding

Trying to output ● (&#9679;) The output in the template cache is &amp;#9679; thus displaying as &#9679; in the browser. The ampersand for my encoding is itself being encoded.

Note: I am putting this in the placeholder attribute of a input element.

gulp-angular-templatecache started by gulp.watch does not write anything

The following gulp watch

gulp.watch( [ templateSrc], ['buildCACHE'] )
        .on( 'change', function ( event ) {
          console.log( ' FILE ' + event.path + ' was ' + 
                                event.type + ', running buildCACHE task ...' );
      });

Starts the buildCACHE task, no errors are given and the output at the command line shows it completes but nothing is ever written to disk

The buildCACHE task works fine when invoked by itself or as part of a larger script, task is below for reference.

gulp.task('buildCACHE',function(){
    gulp.src(templateSrc)
      .pipe(NGTemplatize({standalone:true,base:function(file){
        return path.basename(file.path,'.cache.html');
      }}))
      .pipe(gulp.dest(templateOut));
  });

Not sure what is happening here, all of the other tasks write their output to disk when a watch is fired so I am at a bit of a loss as to why this one is not.

Any ideas?

strange output inside <%= contents %> on windows

Hi,
I'm getting pretty weird output when running angular-template cache.

example:

app structure:

app/
     |-  _assets/
     |-  base/
     |   |-  base.html
...     
index.html

when I run gulp

gulp.task('tpl', function () {
  return gulp.src('app/base/base.html')
    .pipe($.angularTemplatecache())
    .pipe(gulp.dest('app/'));
});

it produeces templates.js with this strange template content:

angular.module("templates").run(["$templateCache", function($templateCache) {$templateCache.put("base.html","(function(module) {\ntry { app = angular.module(\"app-templates\"); }\ncatch(err) { app = angular.module(\"app-templates\", []); }\napp.run([\"$templateCache\", function($templateCache) {\n  \"use strict\";\n  $templateCache.put(\"base/base.html\",\n    \"(function(module) {\\n\" +\n    \"try { app = angular.module(\'base/base.html\'); }\\n\" +\n    \"catch(err) { app = angular.module(\'base/base.html\', []); }\\n\" +\n    \"app.run([\'$templateCache\', function($templateCache) {\\n\" +\n    \"    \'use strict\';\\n\" +\n    \"    $templateCache.put(\'base/base.html\',\\n\" +\n    \"        \'<lbbw-tab-menu></lbbw-tab-menu>\\\\n\' +\\n\" +\n    \"        \'<div class=\\\"action-box\\\" ui-view></div>\\\\n\' +\\n\" +\n    \"        \'\');\\n\" +\n    \"}]);\\n\" +\n    \"})();\\n\" +\n    \"\");\n}]);\n})();\n");}]);

Note: the iffy's inside the template html with those try catch blocks.

So as expected when my angular app tries to boot up and add that string to $templaceCache it throws an error and wont boot.

any ideas?

thanks in advance

module name don't works

This is my pipe:

.pipe(templateCache({
          "filename": "templates.js",
          "options": {
            "module": "App"
          }
        }))

and still the output angularjs module name is "templates".
Am i wrong somewhere? or it is a bug?

How to change the base file path for templates in gulp-angular-templatescache?

I'm having a problem with the paths to my partials inside of the templateCache.js file.

http://stackoverflow.com/questions/31458499/how-to-use-function-to-return-multiple-strings-inside-of-this-gulp-task-pipe-sta

The paths in my templateCache.js are losing the leading folder, for example.

If the path to the partial is panels/tags/tagsPanel.html. Inside the put statement in the templateCache is only shows tags/tagsPanel. Same if it's just 1 folder deep like headers/controlHeader.

Is there an easy way around this with the options?

My example config:

var config = {
    srcPartials:[
        'app/beta/*.html', 
        'app/header/**/*.html',
        'app/help/*.html',
        'app/login/*.html',
        'app/notificaitons/*.html',
        'app/panels/**/*.html',
        'app/popovers/**/*.html',
        'app/popovers/*.html',
        'app/user/*.html',
        'app/dashboard.html'
    ],
    destPartials: 'app/templates/'
};
gulp.task('html-templates', function() {
    return gulp.src(config.srcPartials)
    .pipe(templateCache('templateCache.js', { module:'templateCache', standalone:true }))
    .pipe(gulp.dest(config.destPartials));
});

Add ability to use regexes

I think it would add a lot of functionality to this plugin to allow config options like:

  • stripPrefix - allows you to specify a string/regex to strip from the url
  • stripSuffix - allows you to specify a string/regex to strip from the url

This idea is pulled directly from karma's preprocessor nghtml2js

Path for template files being removed

Let's say I have this in my gulp file:

var paths = [ 
    'Scripts/app/components/chart/chart.tpl.html',
    'Scripts/app/factories/httpErrorInterceptor/httpErrorInterceptor.tpl.html'
];

gulp.src(paths)
    .pipe(angularTemplatecache({ standalone: true }))

The output I get is:

angular.module("templates", []).run(["$templateCache", function($templateCache) {$templateCache.put("chart.tpl.html", ...
$templateCache.put("httpErrorInterceptor.tpl.html","...

Am I correct in thinking that there's no way to get this output below instead?

angular.module("templates", []).run(["$templateCache", function($templateCache) {$templateCache.put("Scripts/app/components/chart/chart.tpl.html", ...
$templateCache.put("Scripts/app/factories/httpErrorInterceptor.tpl.html","...

I don't understand why the path should be shaved off. What if I want to keep them (as I do)?

Looking in index.js of the master source, on line 49, I see that the original file path is being stripped via file.path.replace(base || file.base, ''). Why do this? gulp-templatecache doesn't do this—you have to explicitly tell it to strip out part of the path if you want it removed.

Custom template names

I want to (had to) set name of templates like this: "widget/template1.html"
In your plugin names are auto generated by filename.
Can you add a feature to set template names based on id of script tag?
for example template will be this:

<script type="text/ng-template" id="widget/template1.html">
<div>template content</div>
</script>

and cache name will be this: widget/template1.html

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.