teux / ng-cache-loader Goto Github PK
View Code? Open in Web Editor NEWWebpack loader to put HTML partials in the Angular's $templateCache.
Webpack loader to put HTML partials in the Angular's $templateCache.
Hello,
I fallowed the documentation and created a simple directive:
require('./template.html');
/* @ngInject */
function TimeDirective() {
return {
template: 'template.url'
}
}
module.exports = TimeDirective;
but then looking at generated file path is completely wrong:
function(module, exports, __webpack_require__) {
var v1="<div> Time </div>";
angular.module(["ng"]).run(["$templateCache",function(c){c.put("C:\project\src\scripts\time\template.html", v1)}]);
module.exports=v1;
}
My configuration of loader:
{
test: /template.html$/,
loader: 'ng-cache'
}
I also tried using different values of prefix
parameter. But this was just adding prefix in front of the whole path.
Can I disable resolving relative images in HTML?
In documentation I found
Relative links to the local images are resolved by default.
But I want to disable this behavior, can I do this in config of loader? Or maybe exist workaround ...
Thanks!
The error after very long time...
[master ≡ +2 ~0 -0 | +1 ~17 -0 !]> ./node_modules/.bin/webpack --config webpack.demo.js -d --display-chunks --display-reasons --display-error-details --progress
Hash: 7733c9a6f559e181aea6
Version: webpack 1.12.12
Time: 4200549ms
Asset Size Chunks Chunk Names
bundle.js 1.51 MB 0 [emitted] bundle
bundle.js.map 1.75 MB 0 [emitted] bundle
index.html 739 bytes [emitted]
chunk {0} bundle.js, bundle.js.map (bundle) 1.44 MB [rendered]
[0] multi bundle 28 bytes {0} [built]
+ 49 hidden modules
WARNING in ./~/ng-cache-loader?minimize=false&-url&-removeComments&-removeCommentsFromCDATA&-collapseWhitespace&-conservativeCollapse&-preserveLineBreaks&-removeEmptyAttributes&-keepClosingSlash!./www/components/shared/partials/errorMessages.html
Parse Error: <p ng-message=\"required\" class=\"badge bg-danger text-white\">Este campo é obrigatório</p>\n<p ng-message=\"minlength\" class=\"badge bg-danger text-white\">O valor é muito curto</p>\n<p ng-message=\"maxlength\" class=\"badge bg-danger text-white\">O valor é muito longo</p>\n<p ng-message=\"email\" class=\"badge bg-danger text-white\">Deve ser um e-mail válido</p>\n<p ng-message=\"pattern\" class=\"badge bg-danger text-white\">Não é um valor válido</p>\n\n<span>{{::field.$name}}</span>\n<p ng-message=\"api\" class=\"badge bg-danger text-white\">{{::apiErrorMessages[field.$name] }}</p>\n";
Using unminified HTML
[master ≡ +2 ~0 -0 | +1 ~17 -0 !]>
The errorMessages.html is very simple:
<p ng-message="required" class="badge bg-danger text-white">Este campo é obrigatório</p>
<p ng-message="minlength" class="badge bg-danger text-white">O valor é muito curto</p>
<p ng-message="maxlength" class="badge bg-danger text-white">O valor é muito longo</p>
<p ng-message="email" class="badge bg-danger text-white">Deve ser um e-mail válido</p>
<p ng-message="pattern" class="badge bg-danger text-white">Não é um valor válido</p>
<span>{{::field.$name}}</span>
<p ng-message="api" class="badge bg-danger text-white">{{::apiErrorMessages[field.$name] }}</p>
And in my app.js I have import this file
require('ng-cache?minimize=false&-url&-removeComments&-removeCommentsFromCDATA&-collapseWhitespace&-conservativeCollapse&-preserveLineBreaks&-removeEmptyAttributes&-keepClosingSlash!./components/shared/partials/errorMessages.html');
If I change the html with
<p ng-message="minlength" class="badge">O valor é muito curto</p>
this works.
If I change the html with
<p ng-message="minlength" class="badge mySecondClass">O valor é muito curto</p>
this NOT works.
The follow webpack.config
How can I provide a custom module name based on the entry points provided?
Example:
entry: { 'foo' : projPath + '/foo.js', 'bar': projPath + '/bar.js }, ... { test: /\.html$/, use: [ { loader: 'ng-cache-loader', options: { //tried this syntax as well as ng-cache-loader?module=foo... module: 'test.[root]' } } ] }
I want to end up with two modules created where my templates will be associated to.
angular.module('foo').run( ... ); angular.module('bar').run( ... )
Is this possible with current existing functionality? Btw, I am also using webpack v4.20 and it seems like the custom module name function doesn't work.
How to keep the relative path folders with different depth?
e.g.:
require("path/to/file.html") -> $templateCache.put("path/to/file.html"...
require("path/to/subfolder/file.html") -> $templateCache.put("path/to/subfolder/file.html"...
I didn't found a way to do it for webpack config and available prefix options.
{ test: /.html$/, loader: 'ng-cache?module=app,prefix=???' },
Thank you.
How can I have multiple root for prefix?
For example:
/User/packman/Projects/packman/
├─ app/tmpls/field.html
└─ components/tmpls/yellow.html
loader: "ng-cache?prefix=app and components:**"
//can have
// => ng-include="'tmpls/field.html'"
//or
// => ng-include="'tmpls/yellow.html'"
Seems like, when template is empty after minification it does not generate code for inserting template to $templateCache and there is no v0
variable, which makes browser complaining with module.exports=v0;
.
Hi,
I use this pagination directive in my app, which make use of partial templates.
I can succesfully load the template, but when parsing it throws an error with any kind of ng-click attributes, in this case ng-click="setCurrent(1)"
:
Error: [$parse:lexerr] Lexer Error: Unexpected next character at columns 0-0 [\] in expression [\"setCurrent(1)\"].
http://errors.angularjs.org/1.3.17/$parse/lexerr?p0=Unexpected%20nextharacter%20&p1=s%200-0%20%5B%5C%5D&p2=%5C%setCurrent(1)%5C%22
at eval (webpack:///./~/angular/angular.js?:63:12)
at Lexer.throwError (webpack:///./~/angular/angular.js?:11950:11)
at Lexer.lex (webpack:///./~/angular/angular.js?:11909:16)
at Parser.parse (webpack:///./~/angular/angular.js?:12070:30)
at $parse (webpack:///./~/angular/angular.js?:12789:39)
at Object.compile (webpack:///./~/angular/angular.js?:21688:20)
at applyDirectivesToNode (webpack:///./~/angular/angular.js?:7530:32)
at compileNodes (webpack:///./~/angular/angular.js?:7071:15)
at compile (webpack:///./~/angular/angular.js?:6978:15)
at applyDirectivesToNode (webpack:///./~/angular/angular.js?:7443:33)
Any help would be appreciated! Kind regards
I'm just tried to use ng-cache-loader and got this warning for every file I tried to load.
WARNING in ./~/path/to/file
Critical dependencies:
2:0-22 the request of a dependency is an expression
@ ./~/path/to/file 2:0-22
Hello @teux
Kindly assist.
Webpack 3.10.0 throws an error when processing the html files.
angular curly braces output are rendered as modules instead
e.g.
These relative modules were not found:
* ./\"{{edit.picture}}\" in ./resources/views/partials/ep/user/me.html
With a structure like that:
+-- scripts
+--- foo
+----- a.js
+--- bar
+----- b.js
+-- views
+--- foo
+----- index.html
+--- bar
+----- index.html
+--- shared
+----- index.html
how can one import "views/bar/index.html" AND "views/shared/index.html" within "scripts/bar/b.js" ?
the html files are all called the same "index.html", what can we do to "ng-include" both files?
From this:
require('ng-cache!./my-modal.html')
I get this output:
var v1="module.exports = \"<div id=\\\"myModal\\\" ...;";
ngModule.run(["$templateCache",function(c){c.put("my-modal.html",v1)}]);
This is using the require
syntax from the first example in the readme, does it need updating or has something changed in webpack recently that broke this loader? I am using webpack v1.12.14 and ng-cache-loader v0.0.15.
Good day!
I'm new to this webpack stuff, so there might just be something that I'm missing.
what i do have in my config is:
{
test: /\.html$/,
loader: "ng-cache?prefix=[dir]/[dir]"
}
i've tried both:
require('./pages/page1/page1.html');
and
require('ng-cache!./pages/page1/page1.html');
in both cases the javascript created by webpack then contains the line:
__webpack_require__(14)(["ng"]).run(["$templateCache",function(c){c.put("pages/page1/page1.html", v1)}]);
and this line causes a problem, where it sais
Error: Cannot find module 'ng'.
what am i missing?
Is there any possibility to strip the file ending on each key?
For instance store the template as $templateCache.get('/template1')
instead of $templateCache.get('/template1.html')
Hi,
I have the following files template.html.slm
and another_template.html
and would like to load both with .html
extension only as after parsing the files with slm
they are only html files.
The current [name]
only strips the last extension, how could I achieve this?
Hello @teux
Version detail
webpack: 5.70.0
ng-cache-loader: 0.0.26
I am using below rules in webpack.config
In test.html
<script type="text/ng-template" id="myTemplate"> ... </script>With this line in ts file
require('ng-cache-loader?!../../templates/test.html'),
it shows warning at time of build project, it shows whole template html like
and network call it show blocked status for template fetching like,
Pls guide me for this issue
using 0.0.13, webpack 1.12.2
My movement to webpack is going fantastic. But directives using templateUrl and hence the ng-cache-loader is not working. Only inline templates are which aren't using the cache.
Maybe I'm doing something wrong here, but somehow my partial content X is getting wrapped in the string module.exports="X"
In other words:
require('ng-cache!../partials/huh.html');
var ctrl = function($templateCache) { console.log($templateCache.get('huh.html'); }
define(function(require) {
return function() {
return {
restrict: 'E',
replace: false,
templateUrl: 'huh.html',
controller: ctrl
};
};
});```
and huh.html: <div>huh</div>
The rendered DOM is: <huh class="ng-isolate-scope">module.exports = "<div>huh</div>"</huh>
and console log: "module.exports = "<div>huh</div>""
If attempting to use invalid HTML as template, say, with unbalanced divs, ng-cache-loader fails silently without giving appropriate message. Web pack still points to 'problematic' file futher, but with undescriptive error.
Please add an option either to disable minifier or ignore errors (like in gulp-plumber):
source = htmlMinifier.minify(source, {
removeComments: true,
removeCommentsFromCDATA: true,
collapseWhitespace: true,
conservativeCollapse: true,
preserveLineBreaks: true,
removeEmptyAttributes: true,
keepClosingSlash: true
});
Hi, I have an error with this loader on os x!
Always returns ERROR in ReferenceError: window is not defined.
This is my setup:
loaders: [
//...
{
test: /\.html$/,
loader: 'ng-cache?prefix=[dir]/[dir]&-url'
},
{ test: /\.json$/, loader: 'json-loader' }
]
Affected versions
webpack
: 3.10.0
ng-cache-loader
: >= 0.0.24
Webpack config
{
test: /\.html$/,
loader: 'ng-cache',
...
}
Error
Module build failed: TypeError: Cannot read property 'prefix' of null
Workaround
Append ?
to loader:
loader: 'ng-cache?'
loader-utils#getOptions
returns null
on empty this.query
. Prior to version 0.0.24
, loader-utils#parseQuery
was used, which returned {}
on empty this.query
.
Workaround is simple, but I still consider it a bug.
This is a useful loader. You should add it to the list of loaders 👍
Hi, first of all thanks for the great plugin! However it'd be much better if the options passed to html-minifier could be overridden by config, for instance disabling conservative whitespaces and such. I could prepare a patch if you don't have the time.
Hi,
When I specify a custom module name like this:
module: {
loaders: [
{ test: /\.html$/, loader: "ng-cache-loader?prefix=/templates&module=myTemplates"}
]
},
I get the following error when I load the application in the browser: "Uncaught Error: [$injector:nomod] Module '["myTemplates"]' is not available!
When I omit the custom module parameter, everything works fine.
I'm new to Webpack, so I might be missing something obvious, but looking at the generated code, there seems to be missing some code to create the custom module.
This is the generated code, which results in the above error:
var v1="<div ui-view></div>";
window.angular.module(["myTemplates"]).run(["$templateCache",function(c){c.put("/templates/mytemplate.tpl.html", v1)}]);
module.exports=v1;
If I add one extra line, it works fine:
var v1="<div ui-view></div>";
window.angular.module("myTemplates", []);
window.angular.module(["myTemplates"]).run(["$templateCache",function(c){c.put("/templates/mytemplate.tpl.html", v1)}]);
module.exports=v1;
Browserify, for example, does something similar. It generates the following code for each template:
var ngModule;
try {
ngModule = angular.module('myTemplates');
} catch (e) {
ngModule = angular.module('myTemplates', []);
}
ngModule.run(['$templateCache', function ($templateCache) {
$templateCache.put('/templates/mytemplate.tpl.html',
'<div ui-view></div>');
}]);
Is this a bug?
Hi!
Is using ng-cache-loader better than simply doing `template: require('mytemplate.html')'?
Thank you!
I'm currently getting a bunch of output like 2[{htmlmin-lb}]
when using ng-cache-loader.
The template code being:
<span>{{ node.server_counts.total }}</span>
Looking around in the html-minifier
issues, they're addressed this in 0.7.x: kangax/html-minifier@f1754cd
Could you update it to the most recent version?
Hi,
I couldn't use html-loader
in conjunction but given ng-cache-loader
has support for resolving URLs, would it be possible to support srcset
attribute too?
<img src="illustrations/hourglass.png"> #works
<img srcset="illustrations/hourglass.png"> # does not work
<img srcset="${require('illustrations/hourglass.png')}"> # does not work but would be great
Hi!
I've tried to fiddle around with the options for some time now, but I just can't seem to get this ng-cache-loader to work properly. I always end up getting a 404 in the browser from angular trying to async-load the template instead of fetching it from the $templateCache. Here's my test setup:
Controller, using RequireJS format:
define(['angular', 'ng-cache-loader?module=app.test!../templates/test-partial.tpl'], function(angular) {
angular.module('app.test', [])
.controller('testCtrl', ['$templateCache', function TestCtrl($templateCache) {
// putting it into cache manually works! but we're not doing that now
// $templateCache.put('test-partial.tpl', require('../templates/test-partial.tpl'));
// this outputs undefined
console.log($templateCache.get('test-partial.tpl'));
}]);
});
Template:
<ng-include src="'test-partial.tpl'"></ng-include>
Looking at what the ng-loader generates:
var angular = window.angular, ngModule;
try {
ngModule = angular.module(["app.test"])
} catch (e) {
ngModule = angular.module("app.test", [])
}
var v1 = "<div>Test</div>\n";
var id1 = "test-partial.tpl";
var inj = angular.element(window.document).injector();
if (inj) {
inj.get("$templateCache").put(id1, v1);
} else {
ngModule.run(["$templateCache", function(c) {
c.put(id1, v1)
}
]);
}
module.exports = v1;
//////////////////
// WEBPACK FOOTER
// ./~/ng-cache-loader?module=app.test!./src/app/test/templates/test-partial.tpl
// module id = 499
// module chunks = 0
The generated code seems correct alright, but still the browser tries to load the template asynchronously: angular.js:8661 GET http://localhost:8000/test-partial.tpl 404 (Not Found)
.
As noted above, the $templateCache itself works if I inject it into the controller and put the template into the cache! But querying the $templateCache for the template loaded by ng-cache yields undefined
.
Am I missing something? Is there some other way to debug this?
I have
<ul class="list-unstyled padding-left-15 padding-right-15" ui-sortable="feed.sortableOptions" ng- model="feed.items">
<li ng-repeat="item in feed.items" style="margin-bottom:0px" ng-if="!(item.state==0)">
<div ng-include="item.name" />
</li>
and this
require("ng-cache?!components/widgets/todo.html");
feed.items.push("todo.html");
and finally this;
{ test: /\.html$/, loader: "ng-cache?prefix=[dir]/[dir]" },
It works todo.html gets rendered perfectly but I get wrapped in a span before my html gets rendered the following text;
var v1="
and after todo is rendered on screen wrapped in a span I get the following:
"; window.angular.module(["ng"]).run(["$templateCache",function(c) {c.put("components/widgets/todo.html", v1)}]); module.exports=v1;
What's up with that? Am I doing something wrong?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.