Reputation: 7970
How should one package the HTML templates (aka 'partials') in an Angular.js app when it is concatenated + minified for distribution? Is there a good way of including them in that single file, or should I zip the folder which contains the main.js
, /templates/*.html
and /styles/app.css
subdirectories?
The Require.js optimizer compresses all the JS files to a single file myapp.min.js
that is suitable for distribution, but the HTML files are still referenced as individual files.
As background, the code is in a Node.js server:
public/
/app/main.js
/app/app.js
/app/directives/*.js
/app/filters/*.js
/app/factories/*.js
/app/other/*.js
/app/templates/*.html
After running r.js
, all the files in public/app/**
have optimized twins located in a different directory public/build/**
. But the browser still looks for the templates in their original location, /app/templates/*.html
.
So presumably the client would have to put them in that same directory, which seems like an unfair constraint.
Minifying RequireJS Javascript codebase to a single file
Upvotes: 1
Views: 1173
Reputation: 40296
You have to use the templates through the text!
plugin of RequireJS. E.g. for a directive:
define(["text!app/templates/a.html", "myAngularModule"],
function(template, myAngularModule) {
myAngularModule.directive("theDirective", function() {
return {
template: template, // NOTE HERE
...
};
});
});
Or a route:
define(["text!app/templates/a.html", "myAngularModule"],
function(template_a, myAngularModule) {
myAngularModule.config(function($routeProvider) {
$routeProvider.when("some/path", {
template: template_a, // NOTE HERE
...
});
...
});
});
Alternative, using templateUrl
(just in case it is needed):
define(["text!app/templates/a.html", "myAngularModule"],
function(template_a, myAngularModule) {
myAngularModule.config(function($routeProvider) {
$routeProvider.when("some/path", {
templateUrl: "app/templates/a.html", // can be any value actually
...
});
...
});
myAngularModule.run(function($templateCache) {
$templateCache.put(
"app/templates/a.html", // NAME MUST MATCH NAME ABOVE
template_a
);
});
});
Upvotes: 3