Click here to Skip to main content
15,868,141 members
Articles / Programming Languages / Javascript
Tip/Trick

ASP.NET MVC Bundling/minification with angularjs and Typescript

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
15 Jun 2014CPOL1 min read 23.1K   6   3  
Get information about how to work with angularJs bundling and minification in ASP.NET MVC

Introduction

Many times, we face the issue while using ASP.NET bundling and minification with angular JS application. Here, I am providing a sample so that you will get an idea of how to avoid errors while minification of angularjs application.

While minification of angularJs application, we need to concentrate on dependencies injection.

  • Use $inject
  • Use inline []

Using the Code

I am using ASP.NET MVC 4 + AngularJs + Typescript to create this sample.

Step 1: Create MVC 4 web application.

Step 2: Install typescript on your local machine. Download from here "http://visualstudiogallery.msdn.microsoft.com/fa041d2d-5d77-494b-b0ba-8b4550792b4d" or get installed from VS using "npm install -g typescript"

Step 3: Create "controller/sampleController.ts" / "Directive/taskList.ts" / "filter/transformToHtml.ts " files as shown below:

  • Scripts
  • angular (scripts)
  • angular.js
  • angular-sanitize.js
  • definition (definition files)
  • angular.d.ts
  • jquery.d.ts
  • sample
  • controller
  • sampleController.ts
  • sampleModel.ts
  • sampleScope.ts
  • directives
  • taskList.ts
  • filter
  • transformToHtml.ts
  • main.ts
  • _references.d.ts (should be at the root of application)
  1. Code for "sample/sampleModel.d.ts":
    HTML
    /// <reference path="../../../_references.d.ts">
    
    module Sample {
        'use strict';
    
        export class sampleViewModel {
            constructor() {
            }
            task: string;
            tasks: string[];
        }
    }
  2. Code for "sample/sampleScope.ts":
    HTML
    /// <reference path="../../../_references.d.ts">
    
    module Sample {
        'use strict';
    
        export interface sampleScope extends ng.IScope {
            model: sampleViewModel;
            addTask: () => void;
        }
    }
  3. Code for "sample/sampleController.ts":
    HTML
    /// <reference path="../../../_references.d.ts">
    module Sample {
        'use strict';
        export class sampleController {
            static toString = "sampleController";
            static $inject = ["$scope", "$rootScope", "$sce"];
            private sampleViewModel = new sampleViewModel();
            constructor(
                private $scope: sampleScope,
                private $rootScope: ng.IScope,
                private $sce
                ) {
                    $scope.model = this.sampleViewModel;
                    $scope.model.tasks = ["<b>Sample Task 1</b>", "<b><i>Sample Task 2</i></b>"];
                $scope.addTask = () => this.addTask();
            }
    
            private addTask() {
                this.$scope.model.tasks.push(this.$scope.model.task);
                this.$scope.model.task = "";
            }
        }
    }
  4. Code for "directives/taskList.ts":
    HTML
    /// <reference path="../../../_references.d.ts">
    module directives {
        'use strict';
    
        export class taskList {
            static toString = "taskList";
            static $inject = ['$parse', taskList.directiveFactory];
            static directiveFactory(someParser: ng.IParseService): ng.IDirective {
                return {
                    //Static factory method that returns an ng.IDirective object
                    restrict: 'A',
                    replace: false,
                    transclude: false,
                    scope: {
                        tasks: "="
                    },
                    template: '<div><div>Task Added to List</div><div class="grid">
                    <div ng-repeat="task in tasks track by $index">
                    <span ng-bind-html="task | transformToHtml"></span>
                    </div></div><div>', 
    controller: ["$scope", "$attrs", ($scope, $attrs) => { }] } } } }
  5. Code for "filter/transformToHtml.ts":
    HTML
    /// <reference path="../../../_references.d.ts">
    module filter {
        'use strict';
        export class transformToHtml {
            static toString = "transformToHtml";
            static $inject = ["$sce", transformToHtml.filterFactory];
    
            static filterFactory($sce) {
                return (task) => {
                    if (!task) { return ''; }
                    else {
                        return $sce.trustAsHtml(task);
                    }
                };
            }
        }
    }
  6. Code for "Scripts/main.ts":
    HTML
    /// <reference path="../_references.d.ts" />
    
    module main { 'use strict'; var appModule = angular.module("app", ["ngSanitize"])
    
    .filter(filter.transformToHtml.toString, filter.transformToHtml.$inject)
    
    .controller(Sample.sampleController.toString, Sample.sampleController)
    
    .directive(directives.taskList.toString, directives.taskList.$inject)
    
    }
  7. Add all the above references should be included in "_references.d.ts ":
    HTML
    /// <reference path="Scripts/definitions/angular.d.ts" />
    /// <reference path="Scripts/Sample/filter/transformToHtml.ts" />
    /// <reference path="Scripts/Sample/controller/sampleController.ts" />
    /// <reference path="Scripts/Sample/controller/sampleScope.ts" />
    /// <reference path="Scripts/Sample/controller/sampleModel.ts" />
    /// <reference path="Scripts/Sample/directives/taskList.ts" />
  8. Now compile main.ts using "tsc.exe" and generate final .js file inside as "\Scripts\minificationSample.js " from the command prompt:
    XML
    tsc.exe "<Application Path>\MinificationSample\Scripts\main.ts" 
    --out "<Application Path>\MinificationSample\Scripts\minificationSample.js"
  9. Now open "BundleConfig.cs" file and add JS files into it and set "BundleTable.EnableOptimizations" option as "true":
    C#
    bundles.Add(new ScriptBundle("~/Scripts/minified").Include(
                            "~/Scripts/angular/angular.js",
                            "~/Scripts/angular/angular-sanitize.js",
                            "~/Scripts/minificationSample.js"
                            ));
                BundleTable.EnableOptimizations = true;
  10. Create "sample.cshtml" add the following HTML in it and create Action method for the same:
    HTML
    @{
        Layout = null;
    }
    
    <!DOCTYPE html>
    
    <html ng-app="app">
    <head>
        <meta name="viewport" content="width=device-width" />
        <title>Minification Sample</title>
        @Scripts.Render("~/Scripts/minified")
        <style>
            div {
                padding: 10px;
            }
    
            .grid {
                width: 500px;
            }
    
            .grid {
                background-color: Green;
            }
    
                .grid div:nth-child(even) {
                    background-color: #E0E0E0;
                }
    
                .grid div:nth-child(odd) {
                    background-color: #cccccc;
                }
        </style>
    </head>
    <body ng-controller="sampleController">
        <div>
            <h1>Task List</h1>
        </div>
        <div>
            <div>
                <div style="vertical-align:central;width:8%;float:left">
                    Task:<br />
                    (* You can add HTML tags)
                </div>
                <div style="width:15%;float:left">
                <textarea type="text" ng-model="model.task" ></textarea>
                </div>
            </div>
            <div>
                <input type="button" ng-click="addTask()" value="Add Task" />
            </div>
        </div>
        <div>
            <div task-list tasks="model.tasks"></div>
        </div>
    </body>
    </html> 

Now run your application and check your bundling and minifications. I have also attached a sample with this article.

If you need any help, just let me know.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
India India
Web developer having experience in MVC4, AngularJs, Typescript

Comments and Discussions

 
-- There are no messages in this forum --