Bundling Angular for production in Visual Studio 2015

There are many ways of bundling Angular SPA. One of the ways I followed is Code Project by  This article recommends gulp task script and SystemJs-builder.

One thing I couldn’t make it work even I followed this article was bundling angular app for a production environment. This is because I started my Angular app following the Angular official tutorial so that app is slightly different from what’s in the Code Project and probably I used different versions of dependency.

I had a few issues when I couldn’t make a production ready bundle.

  1. As I kept using SysntemJs for production, the Angular app had to read many javascript files while loading the page, which caused slow page loading.
  2. Browser cache prevented users from loading updated new javascript of the Angular app.

The solution

Use SystemJs-Builder. The great thing about using systemjs builder for a production environment is that it helps to bundle all Angular dependency files and my Angular into a single minified javascript file. This can help my 2 issues. It’s like magic.

Actually, I was already using systemjs builder as suggested in the Code Project article to bundle Angular dependency files into a single angular4-dev-min.js. However, it wasn’t working for the buildForProduction stage, which uses a buildStatic function.

Main error I experienced was “Error on fetch for app.module” and “not found app.XXX.html”, which is templates of my Angular app. Clearly, it was related to path configuration. As my app was working well when loaded by systemjs, it looks to me a bug of systemjs.

The first error resolved by the workaround in the the bug comment. as below.

Use a .js extension for all my Angular app files to import. As fetch error keep occurred other js files, I had to add .js for all import in all Angular .ts files.

import { AppModule } from './app.module.js';
import { AppRoutingModule, routableComponents } from './app-routing.module.js';

The second error seems only happened to me.  The solution was adding a path(/App) in @component section. The original Code Project used ‘./App‘, which didn’t work for me, because it added extra ‘/App’ path like ‘/App/App’ when running the app in debug mode.

@Component({
 moduleId: module.id,
 selector: 'my-app',
 templateUrl: '/App/app.component.html,
 styleUrls: ['/App/app.component.css']
})

Just to share what dependency I used, I show the part of package.json below

"@angular/common": "^4.0.0",
"systemjs": "0.20.18",
"systemjs-builder": "^0.16.6",

Just one issue with the solution above is that absolute path for styleUrls doesn’t work with Angular2 or 4. This is an Angular bug and workaround is putting CSS in HTML file keeping the URL as is for now.

Leave a comment

Your email address will not be published.