Hani Hani - 1 year ago 638
Javascript Question

Angular2 bundling and minification

ASP.NET (or gulp) will take care of bundling and minification. However, the problem i came across is rather different. Per Angular2's tutorials, the view HTML is embedded within the component itself. There is a way, using TypeScript, to separate that into a

files. Here's how:

/// <reference path="./view-declaration.d.ts" />
import {html} from '/app.html!text';
template: html

And faking
as a module in

declare module '/app.html!text' {
var html:string;
return default html;

This is using SystemJS with its text plugin. This will not generate
files which means HTMLs can't be bundled along the transpiled

So questions is, how do you separate the HTML from JavaScript, but also be able to bundle them properly?

Also to note, this approach is just the same as setting the
on your component. Both of which defeat the purpose of bundling and reduction of server hits per component. The offered solution from Angular2 is to use string and set
on a component. This is pretty far from reality of junior developers and code reviews (yea not gonna get the whole code base in order to run and see if browser complains about a non-closed tag!).

Answer Source

As it turns out, you'll need to use templateUrl for development, but replace that with template during the bundling and minification. This is the gulp task for the job:

var gulp = require('gulp'); //install 'gulp' via npm
var uglify = require('gulp-uglify'); //install 'gulp-uglify' via npm
var concat = require('gulp-concat'); //install 'gulp-concat' via npm
var replace = require('gulp-replace'); //install 'gulp-replace' via npm
var fs = require("fs"); //already available in Visual Studio and of course NodeJS

gulp.task('bundle:js', function () {
    return gulp
        .pipe(replace(/templateUrl.*\'/g, function (matched) {
            var fileName = matched.match(/\/.*html/g).toString();
            var fileContent = fs.readFileSync(fileName, "utf8");
            return 'template:\'' + fileContent.replace(/\r\n/g, '') + '\'';
        .pipe(gulp.dest('my bundle folder'))
        .pipe(gulp.dest('my bundle folder'));

This is to match .html files and the template URL, but it can be tweaked if needed.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download