Angular Build with Webpack from Scratch – Part 2

Angular Build with Webpack Hero

Derived from photo by Yann Caradec / flickr.com, CC BY-SA

This is the second post in a two-part series getting started with webpack from scratch. The first part covered how to configure the Angular-specific portion of a webpack build. This post walks through how to configure the HTML, CSS, and development server. It builds upon the configuration started in part one.

If you want to jump straight to the code, the completed demo is on GitHub.

Webpack Context

As webpack begins to handle more of the application, it becomes necessary to configure multiple entry points for the build. Part one configures the full path for the single entry file. You could follow the same pattern with any new entry files. You could instead set the context configuration property.

The context property sets a directory as the location where file paths resolve. Instead of combining the paths of each entry file, you configure the base path and then specify the individual file names. This is how part one configured the single entry for webpack:

const path = require('path');
const source = path.resolve(__dirname, 'src', 'index.ts');

module.exports = {
    entry: source,
    // ...
};

To prepare for multiple entries, refactor the entry to use the context property as well:

const path = require('path');
const source = path.resolve(__dirname, 'src');

module.exports = {
    context: source,
    entry: [
        './index.ts'
    ],
    // ...
};

Note: The __dirname variable is a string from Node.js providing the current module's directory.

Using the context property is optional but it helps to remove repetitive path combining logic from your configuration.

HTML Build

Single-page applications are named this way because they typically contain one HTML document that loads the scripts to bootstrap the application. Angular is no exception and there is a handy plugin for webpack called HtmlWebpackPlugin to dynamically configure the HTML page.

The initial configuration for HtmlWebpackPlugin is straightforward. Import the module from its npm package, html-webpack-plugin, and then add it to the plugins property of the webpack configuration.

const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    // ...
    plugins: [
        new HtmlWebpackPlugin()
    ]
};

By default, the plug-in gives you a boilerplate HTML file for your application. You can however, supply it with a template through the module's constructor arguments. Keep in mind that when using a template, the HtmlWebpackPlugin automatically adds a script element referencing the output of the webpack build so ensure you haven't added the script reference multiple times. This is how to specify the template for HtmlWebpackPlugin:

module.exports = {
    // ...
    plugins: [
        new HtmlWebpackPlugin({
            template: './index.html'
        })
    ]
};

Now you have a webpack build that includes the JavaScript and HTML for your application where the bundle is automatically referenced in the output index.html file. Try it by running npm run build at the command line and inspect the output in the dist directory. The HtmlWebpackPlugin has many great extensions. You can find some of them listed in the project's README file.

CSS Build

The final portion of the Tour of Heroes to address is the global CSS. In the first part of this series, you configured webpack to load any CSS files that are referenced by Angular components. However, the application has global CSS defined in the styles.css file. This file includes style rules relevant to the overall look and feel of the application so it makes sense to keep this outside of the individual components` CSS.

The configuration already processes CSS for the components but this configuration won't work for the global CSS. The first thing is to define the boundary between when webpack should process CSS for components and when webpack should process the global CSS. Looking at the application, everything in the directory .\src\app\ needs to be configured for the angular2-template-loader where other CSS in the .\src\ directory should be bundled and included as a linkelement in the index.html file.

Define a variable for the .\src\app\ path and use the include property on the raw-loader configuration:

const source = path.resolve(__dirname, 'src');
const appDirectory = path.resolve(source, 'app');

module.exports = {
    // ...
    module: {
        rules: [
            // ...
            {
                test: /\.(css|html)$/, 
                include: appDirectory,
                loader: 'raw-loader'
            },
            // ...
        ]
    },
    // ...
};

To process the non-component CSS, use the ExtractTextPlugin. This plugin is essentially a wrapper that provides bundling functionality. It leverages other loaders' import logic to load the CSS content. In the end, you get a combined CSS file. Import the plugin from its npm package, extract-text-webpack-plugin. You also use the style-loader and css-loader npm packages for their respective CSS loaders.

Add the following to the rules array of the webpack configuration:

const ExtractTextPlugin = require('extract-text-webpack-plugin');

const source = path.resolve(__dirname, 'src');
const appDirectory = path.resolve(source, 'app');

module.exports = {
    // ...
    module: {
        rules: [
            // ...
            {
                test: /\.css$/,
                exclude: appDirectory,
                loader: ExtractTextPlugin.extract({ 
                    fallback: 'style-loader', 
                    use: 'css-loader?sourceMap' 
                })
            },
            // ...
        ]
    },
    // ...
};

You see this configuration loads files ending in the .css extension and excludes the appDirectory CSS. Remember, the appDirectory path contains your Angular code and undergoes a different build process than global styles.

The ExtractTextPlugin is configured as both a loader and a plug-in. To configure the plug-in portion of ExtractTextPlugin, add it to the plugins array. Provide a name for the final output bundle, for example styles.css.

module.exports = {
    // ...
    plugins: [
        // ...
        new ExtractTextPlugin('styles.css')
    ]    
};

Note: This tutorial uses styles.css as both the name of the input file and the output file. Feel free to customize this to help ensure you understand which piece of the configuration is related to inputs and which is related to outputs.

Finally, webpack needs to know about the existing Tour of Heroes styles.css file so add it as an entry in the configuration:

module.exports = {
    context: source,
    entry: [
        './index.ts',
        './styles.css'
    ],
    // ...
);

Now that the CSS is auto-generated, the HtmlWebpackPlugin and ExtractTextPlugin work together to add a link to the index.html template file. Remove any existing links to styles.css from the index.html file.

The ExtractTextPlugin has several different options and uses so it's worth taking a look at its documentation.

At this point, your webpack build is complete. Try it with npm run build to see the output. The final HTML template and webpack configuration should have the following contents:

<html>
<head>
  <base href="/">
  <title>Angular 2 Tour of Heroes</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
</head>

<body>
  <my-app>Loading...</my-app>
</body>

</html>
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');

const source = path.resolve(__dirname, 'src');
const destination = path.resolve(__dirname, 'dist');
const appDirectory = path.resolve(source, 'app');

module.exports = {
    context: source,
    entry: [
        './index.ts',
        './styles.css'
    ],
    output: {
        filename: 'index.js',
        path: destination
    },
    resolve: {
        extensions: ['.ts', '.js']
    },
    module: {
        rules: [
            {
                test: /\.ts$/,
                loaders: [
                    'awesome-typescript-loader',
                    'angular2-template-loader'
                ]
            }, 
            {
                test: /\.ts$/,
                loader: 'webpack-replace',
                query: {
                    search: 'moduleId: module.id,',
                    replace: ''
                }
            },
            {
                test: /\.css$/,
                exclude: appDirectory,
                loader: ExtractTextPlugin.extract({ 
                    fallback: 'style-loader', 
                    use: 'css-loader?sourceMap' 
                })
            },
            {
                test: /\.(css|html)$/, 
                include: appDirectory,
                loader: 'raw-loader'
            },
        ]
    },
    plugins: [        
        new HtmlWebpackPlugin({
            template: './index.html'
        }),
        new ExtractTextPlugin('styles.css')
    ]
};

Development Server

The webpack development server integrates with webpack to provide many great features to aid your development. This functionality is installed with the webpack-dev-server npm package. The server automatically watches for changed files and refreshes the browser once a new compilation is complete. To improve performance, the webpack development server keeps the generated contents in memory as opposed to writing it to disk.

To setup a project for the webpack development server, create an npm script. For this tutorial, use the npm start command. There are several command line options available to configure the development server. Use the --open option to have the development server automatically open the default browser to the server's port on localhost:

"scripts": {
    "start": "webpack-dev-server --open",
    ...
}

While the development server has many configuration options, this tutorial covers two that are relevant to Angular developers: devtool and historyApiFallback. The devtool property specifies a source map type to aid in debugging at runtime. Go ahead and set the property to 'source-map'.

Then under the devTool configuration property, set the historyApiFallback property to true. This property tells the server to always return the index.html contents when a route is not available on the server. This is very useful when using client-side routing so that the server defers routing responsibility to Angular's router. Define these properties in your webpack configuration:

// ...
module.exports = {
    // ...
    devtool: 'source-map',
    devServer: {
        historyApiFallback: true,
    }
};

Save your configuration and type npm start at the command line to see webpack build and serve the application.

Final Thoughts

Now you have a starting point for your webpack build and more importantly, you understand how these pieces work together. Many of the more advanced webpack examples you see online use these pieces as their foundation so you can more easily add additional features to the build as you need them.

If you want to see this build in action, look at the repository on GitHub.

What are the next steps on your webpack journey? Which aspects of the build are still causing issues for you? Please sound off in the comments.

Angular Build with Webpack from Scratch

Angular Build with Webpack Hero

Derived from photo by Yann Caradec / flickr.com, CC BY-SA

This tutorial walks through creating a webpack-based build for the Angular Tour of Heroes sample application. By the end, you will have a basic build and development server with automatic refresh and source maps.

The tutorial is divided into two parts. In this first part, you setup the project and create the Angular-specific build. In part two, you process the other files of the application and setup the development server. Read part two here.

More importantly, you will understand what each piece of the webpack configuration does. Why is it important? How does it relate to other pieces of the build? This understanding is critical when you inevitably want to modify or add new webpack functionality.

Migrate Tour of Heroes

First, create a new directory for your project. Before copying any of the Tour of Heroes code into your repository, create a folder named src in the root of your project. This folder will house the source code related to the browser-based Angular web application. In contrast, the project's root directory is the place for configuration files for the build and overall project. These specific directory names and locations aren't required but consider partitioning your project's source code according to the application's concerns, e.g. client versus configuration.

Tip: Clone the Angular Tour of Heroes sample application locally to copy files easily.

Create the src directory within your project and copy the entire app directory, index.html, and styles.css files from Angular Tour of Heroes into the newly created src directory. Then, copy the tsconfig.json and package.json files into the project's root directory.

Your application structure should look like this:

├── src
|   ├── app
|   |   └── (...)
|   ├── index.html
|   └── styles.css
├── package.json
└── tsconfig.json

Now, make a couple modifications to the copied content. First, delete the src\app\main-aot.ts file. Ahead-of-Time (AOT) compilation is outside the scope of this tutorial and keeping this file causes a TypeScript compilation error.

Next, modify the packages in the package.json file. Since the entire build system is changing, replace the package list under devDependencies with this list:

"devDependencies": {
    "@types/node": "^6.0.45",
    "angular2-template-loader": "^0.6.0",
    "awesome-typescript-loader": "^3.0.3",
    "css-loader": "^0.26.1",
    "extract-text-webpack-plugin": "^2.0.0-beta.5",
    "html-loader": "^0.4.3",
    "html-webpack-plugin": "^2.16.1",
    "raw-loader": "^0.5.1",
    "rimraf": "^2.5.2",
    "style-loader": "^0.13.1",
    "typescript": "~2.0.10",
    "webpack": "2.2.0",
    "webpack-dev-server": "2.2.0-rc.0",
    "webpack-replace": "^1.0.0"
}

For now, don't worry about these packages as they are noted throughout the relevant sections of the tutorial.

Now that the list of packages is updated, run npm install from the terminal to install the required packages.

Finally, replace the existing npm scripts with a single script to invoke the webpack build:

"scripts": {    
    "build": "rimraf dist && webpack"
}

Note: If you attempt to run this script from a tasks.json file in Visual Studio Code, webpack might throw an error. To work around, run the npm script from the terminal instead.

This script calls the npm package utility rimraf to clear the contents of the dist directory and then calls webpack. The dist directory will be where webpack saves the build output.

Going forward, use the build script by invoking the command npm run build in the terminal to create the build. As you iterate your build configuration, use this command to verify the output.

TypeScript Build

In most cases, an Angular application consists of TypeScript files using ES2015 modules with HTML templates and styles defined either in line with components or in external files. The webpack build needs to understand how to process this structure and bundle it into a format the browser understands.

The Angular framework requires a couple polyfill scripts from core-js and zone.js. In Tour of Heroes, these scripts are included in the index.html file prior to loading the application. Being that the bundling process uses ES2015 import statements to create the bundle, move these script references to a new file called index.ts. Later, when processing the index.html file, the build will reference this new script. Place the index.ts file in the src directory with the rest of the Angular application and add this code:

// Polyfills
import 'core-js/es6';
import 'core-js/es7/reflect';
import 'zone.js/dist/zone';

// App
import './app/main.ts';

In addition to the polyfills, this file also imports the main.ts script to bootstrap the Angular application.

Now, it's time to create the webpack configuration. By default, webpack looks for a file at the root of the working directory named webpack.config.js. Go ahead and create this file and add the following contents:

const path = require('path');

const source = path.resolve(__dirname, 'src', 'index.ts');
const destination = path.resolve(__dirname, 'dist');

module.exports = {
    entry: source,
    output: {
        filename: 'index.js',
        path: destination
    },
    resolve: {
        extensions: ['.ts', '.js']
    },
    module: {
        rules: [
            {
                test: /\.ts$/,
                loaders: [
                    'awesome-typescript-loader'
                ]
            }
        ]
    }
};

At a high level, this file contains three variables: path, source, and destination. The path variable represents an imported npm module to assist in concatenating the required file and directory paths represented by source and destination.

The configuration also defines an object literal as the module's exports. The object literal is the webpack configuration and has the following properties: entry, output, resolve, and module. The entry property points to the file where webpack begins to construct the dependency tree, in this case, the index.ts file you created earlier. The output property defines the output file's name and path, in this case, dist\index.js.

The resolve property assists loading the TypeScript files. Because the import statements don't typically use a file extension, webpack uses the extensions defined in resolve.extensions to reconcile the imports. The compilation of the TypeScript files is ultimately handled by the awesome-typescript-loader. This loader is included in the project as an npm package defined in the package.json file.

The module.rules property is an array of objects that represent which tools load which files. In webpack, there is a concept of a loader. Loaders are an extension point which customize how code is processed by the webpack build. The defined loaders array is used only when an import matches the regular expression supplied in the test property.

The awesome-typescript-loader compiles TypeScript into JavaScript. The loader is used only for files that match the regular expression /\.ts$/ as defined in the test property.

With this configuration defined, test your build by typing npm run build in the terminal. Look at the newly created dist folder to see the result – one single JavaScript file index.js. Examine the contents and you will start to get a sense of how webpack packages the application dependencies.

Angular Component HTML and CSS

Compiling TypeScript to JavaScript is the first step in an Angular build. Now, you must include the contents of any external templates and styles. Components define these resources in the @Component decorator:

@Component({
    templateUrl: 'my-template.html',
    styleUrls: [ 'my-styles.css' ]
})
export class MyComponent { }

The angular2-template-loader is listed under defDependencies in the package.json file. It extends webpack to load these external files and place the contents in line with the component. The resulting code looks something like this:

@Component({
    template: '<h1>Hello World!</h1>',
    styles: ['h1 { color: blue }']
})
export class MyComponent { }

The angular2-template-loader requires that webpack understands how to load HTML and CSS files. Therefore, add another rule to the rules list to test for .css and .html files and use the raw-loader package. The raw-loader is a simple loader that emits the contents of a file as a string.

This is how the new rules configuration looks with these changes:

rules: [
    {
        test: /\.ts$/,
        loaders: [
            'awesome-typescript-loader',
            'angular2-template-loader'
        ]
    }, 
    {
        test: /\.(css|html)$/, 
        loader: 'raw-loader'
    },
]

Run the build again to test that the new configuration works. To verify that the HTML templates are included, perform a search in the emitted index.js file for a piece of code from one of the external templates such as {{hero.name}}.

The moduleId Problem

The Tour of Heroes application is designed to use SystemJS. Instead of combining the ES2015 modules into one bundle on the server, SystemJS dynamically loads all of the modules it needs when the application runs in the browser.

To assist the dynamic loading process, developers oftentimes configure the moduleId property like this:

@Component({
    moduleId: module.id,
    templateUrl: 'my-template.html',
    styleUrls: [ 'my-styles.css' ]
})
export class MyComponent { }

The value passed by module.id is populated at runtime by SystemJS. Since SystemJS is not there anymore to populate the property, it is not defined and Angular doesn't like this. It throws the error 'moduleId should be a string in "AppComponent".

One way to get around this is to manually change all of the files by removing the moduleId definitions. After all, who needs all of this boilerplate code anyway? However, you may not always have access to this code. You may be using code authored by a third party which hasn't in lined the templates as part of a build. They have moduleId defined so that consumers can use SystemJS if they choose.

For this tutorial, instead of manually removing the moduleId settings, webpack will do it for you. Use the webpack-replace loader (another npm package) to search for the moduleId settings and remove them.

The webpack rules configuration now looks like this:

rules: [
    {
        test: /\.ts$/,
        loaders: [
            'awesome-typescript-loader',
            'angular2-template-loader'
        ]
    }, 
    {
        test: /\.ts$/,
        loader: 'webpack-replace',
        query: {
            search: 'moduleId: module.id,',
            replace: ''
        }
    },
    {
        test: /\.(css|html)$/, 
        loader: 'raw-loader'
    }
]

Run your build again using npm run build and search in the output for moduleId: module – the search should return no results.

Finally, the webpack.config.js file looks like this:

const path = require('path');

const source = path.resolve(__dirname, 'src', 'index.ts');
const destination = path.resolve(__dirname, 'dist');

module.exports = {
    entry: source,
    output: {
        filename: 'index.js',
        path: destination
    },
    resolve: {
        extensions: ['.ts', '.js']
    },
    module: {
        rules: [
            {
                test: /\.ts$/,
                loaders: [
                    'awesome-typescript-loader',
                    'angular2-template-loader'
                ]
            }, 
            {
                test: /\.ts$/,
                loader: 'webpack-replace',
                query: {
                    search: 'moduleId: module.id,',
                    replace: ''
                }
            },
            {
                test: /\.(css|html)$/, 
                loader: 'raw-loader'
            }
        ]
    }
};

The working directory structure now looks like this:

├── dist
├── node_modules
├── src
|   ├── app
|   |   └── (...)
|   ├── index.html
|   ├── index.ts
|   └── styles.css
├── package.json
├── tsconfig.json
└── webpack.config.js

That's All for Now

This tutorial has taken you through the basics of building the Angular portion of the application. However, there are more pieces of the application that require processing. In part two, you handle the index.html and CSS portions of the application. In addition, you learn how to configure the webpack development server to run the application. Continue with part two here.

Angular and the Server

Angular and the Server Header

Derived from photo by jeanbaptisteparis / flickr.com, CC BY-SA

Coming from an ASP.NET background, developers are familiar with the File, New Project… experience. This is the process to setup a new project in Visual Studio – typically from a template to help you get started effectively.

These starter projects include everything in the box. They have UI rendering, authentication, sample data APIs, and more. And while they are great for getting started, they may not be the best design for the application you are building.

When it comes to building an Angular application, how should it integrate with the server-side application if at all? What design options are available to you and how do you know which is the right one? This is an often-overlooked topic in Angular-focused material. One the other end, server-side articles tend to encourage using server-side features without considering that you are using a very powerful front-end framework already.

This article details several application responsibilities and groups them in terms of their integration with the host application. For the purposes of this article, the host application is the server-side application that sits beneath your Angular application and serves it to the browser/client. (Spoiler alert, there might be NO application sitting beneath your Angular application.) The Angular application consists of the TypeScript and/or JavaScript you write against the Angular framework.

Level 0 – No Server Application

This level includes features that are configurable to have no server-side dependency. This means that when the application runs, Angular handles these features without requiring the server to process any of the logic. This configuration may be desirable especially when static file hosting is the preferred deployment option.

Even though there is no run-time server dependency, you can still leverage the power of a build to optimize your application. These are some of the features you can configure with no server-side backend.

Routing

The Angular router is optionally configured to use the hash URL style. In this configuration, each route is represented in the URL following the hash symbol, like example.com/#/about or example.com/#/products/1. The main benefit is that when someone enters this URL into the browser, they are going to the same endpoint each time, example.com. When the application loads, the router kicks in and navigates to the correct view.

Internationalization (i18n)

Angular includes utilities to internationalize applications. There are several phases to this process which you can read about in the documentation. At the end, you are left with multiple versions of your application that are deployed to their own directory as static files. At this point, there are several options for routing the user to the correct version of the application. The choice can be left to the user in the UI or the application can read the language settings in the browser to automatically route to the correct locale.

View Rendering

One of the first highlights of the Angular framework was its rendering. Being able to bind a JavaScript object to a template and see the data and events wire themselves up was almost magic. Angular accomplishes this in the browser and while server frameworks have their own rendering engines, you can generally rely on client-side rendering for your views when using Angular.

Level 1 – Host Application Integration

This level consists of functionality where the host application and the Angular application work together to produce the runtime functionality. While the server may not know intimately about the Angular application, both the server and client must be configured in a complimentary manner and make assumptions about the other's behavior.

Routing

As opposed to the hash style URL discussed earlier, the more common HTML 5 pushState style URL depends on server support. These URLs lack the hash symbol, for example example.com/about or example.com/products/1. The issue here is that when someone navigates to your application the first time using one of these URLs, the Angular application doesn't have a chance to handle the route. Instead, the server receives the request first and then returns the Angular application to the client to then complete the routing process. You can see an example with ASP.NET Core here.

Authentication

Sometimes, there are reasons to lock down your Angular application to only authorized users. While the Angular application could handle this based off of Web API authentication, you also have the option to authorize with the host application. For instance, the first time someone navigates to your web application, the server can return the 'not authorized' messaging without returning any of the Angular code to the browser.

View Rendering

As mentioned previously, Angular's rendering is more than capable of generating your application's UI. Generally, this rendering occurs in the browser. However, applications optimized for SEO and time-to-load performance, benefit from server-side rendering.

This is where Angular Universal fits in. Instead of using the server framework's view engine, Angular Universal renders Angular templates server-side. The browser receives the HTML and CSS to display the page immediately without client-side rendering. Subsequent views are loaded via AJAX and rendered on the client to reduce subsequent payload sizes. The framework supports both Node.js and ASP.NET Core backends.

Using Angular Universal does increase complexity and imposes certain restrictions in how you write your Angular application. Be sure that if you need this extra performance boost that you understand the trade-offs. Read more about it on GitHub.

Internationalization

Internationalization is an area where the host application may not have a direct role but may need to assist integrated routing, authentication, and/or rendering to provide the desired experience.

Logging

Logging also doesn't necessarily represent a tight integration between the host application and the Angular application. However, consider that as you increase the server's role with routing, authentication, and/or rendering, you should consider logging any errors resulting from this increased responsibility.

Level 2 – Web APIs

These dependencies are server-side dependencies. However, they do not have to live within the same web application hosting the Angular application. By keeping these dependencies in their own code base, there are many advantages. Builds and deployments are performed only for the applications that have changed. The APIs are built with whichever technology the team and/or company decide so long as it works over a common protocol – typically HTTPS. If you are familiar with the concepts of Web APIs and/or Microservices, this group encompasses those concepts.

Web APIs

Some examples of web API responsibilities that an application requires include data access, logging, and usage analytics. Interestingly, none of these concerns require any knowledge of the Angular application. In fact, they could serve many different front-end applications.

Authentication

Authentication at this level is typically handled directly between the Angular application client and the Web API server. There are many ways to do this but today's solutions generally use some form of JSON web tokens to maintain the user's identity.

Internationalization

At this level, any assets requiring i18n would be handled by the web API using server-side techniques. Again, this has no coupling to the Angular application beyond the API contract.

A Case for Bundling

Sometimes, applications are small and the API that they access is small. In this case, you may decide to keep this functionality together in the same application. They share the same build and the same deployment. Sometimes the effort to split these functions isn't greater than the payoff.

In this case, consider your development and design carefully as to avoid creating unnecessary coupling between the concerns. The web API may one day 'grow up' to need its own project so develop accordingly.

Final Thoughts

Every application is different. Hopefully by reading about how application concerns create dependencies between the server and the Angular application, you can apply these considerations to your own architecture.

One thing you might have noticed, there's no discussion of development tools that integrate with the server. This is a topic for a future post so stay tuned.

Ultimately, there is no one way to design an application. However, by knowing your options, you're better equipped to make lasting design decisions for your project.

What do you think? Is there functionality you prefer to run on the server? The client? Please share in the comments.

Great Angular, ASP.NET Core Starter Templates

Great Angular, ASP.NET Core Starter Templates Title

This post exists to provide hope. After the somewhat hesitant reaction to last week's webpack post, this post highlights two great Angular and ASP.NET Core starter templates. These starter projects not only contain configurations for webpack 1 and webpack 2, there are a ton of other Angular and ASP.NET features implemented for you.

ASP.NET Core Template Pack

ASP.NET Core Template Pack - Angular Starter

The first project template to note comes from the ASP.NET Core Template Pack by Mads Kristensen. The template pack is a Visual Studio Extension containing multiple templates for ASP.NET Core. The collection includes a helpful Angular template.

Key Features

The hallmark feature of the template is Angular Universal. This framework enables server-side Angular rendering when the application is initially requested from the server. Angular Universal decreases the initial page load time by rendering the first request on the server instead of requiring the client to wait for the application to download before rendering. Subsequent route changes are all rendered client-side. For any application that requires minimum load times, this framework is a must-see.

The template also uses webpack version 1. For anyone working on integrating webpack into their applications, every example helps. This template doesn't use the latest loaders that the folks on the Angular side of the community are using. It does however accomplish the primary goal by compiling combined scripts. And being that it's using Angular Universal, there are webpack configurations for both the client application and the server rendering portion.

The template also implements webpack's hot module replacement feature. This is a development feature where the client-side code is replaced in the browser via a WebSocket when the source module is edited on the file system. If you've ever used a development server with automatic refresh like Browser Link or Browsersync, then it's like that – except without the full page refresh. You should check out the template just to try out this feature – you may never go back.

The previously mentioned features are configured with the help of Steve Sanderson's ASP.NET Core JavaScript Services. This library is part of ASP.NET Core on GitHub and provides useful integrations for single-page application (SPA) frameworks including Angular. The template includes simple, foundational examples for routing and data access as well as Docker container configuration.

Gotchas

Currently, if you are looking for the very latest in front-end Angular features, this template doesn't have them. It's using webpack version 1 versus webpack version 2 and doesn't include all of the niceties that have been introduced with newer webpack loaders such as awesome-typecript-loader and angular2-template-loader.

Also, if you see an error like this when starting the template, it means you have to specify a prior version of ASP.NET using the global.json file.

Template Error

You can read more about the solution on GitHub.

Bottom Line

This is a stable template that highlights the main integration points between ASP.NET Core and Angular. For now, it might not have the most up-to-date client-side features but you can imagine these will come as the tooling comes to a final release (or when we all submit pull requests). Being a Visual Studio extension, it is optimized for the Visual Studio IDE and it provides a nice starting point.

To view the source for this template, check out its GitHub repository.

ASP.NET Core & Angular2 Universal Starter (Angular2Spa)

ASP.NET Core & Angular2 Universal Starter Diagram

This might be the best Angular on ASP.NET Core template available right now. It's actively developed by a member of the Angular Universal team, Mark Pieszak.

In fact during the course of writing this review, he fixed an issue that I was experiencing while working with the template for this article. The template contains some of the latest techniques and frameworks for building Angular applications on ASP.NET or otherwise.

Key Features

You can think of this project as a superset of the template currently in the ASP.NET Core Template Pack. It has the same base level of features and then adds on top of it. This template works in Visual Studio. It also contains configuration files to run in Visual Studio Code, complete with key bindings to initialize the dotnet build. It even uses the newer ASP.NET Core 1.1 assembly versions.

For the front-end tooling, the template uses webpack version 2 including many new loader patterns that you find in the Angular documentation. The example also makes use of an RxJS-based, Redux-like store via the NgRx library.

To help keep your code styles on par, this template uses codelyzer. Built on top of TSLint, codelyzer provides linting for TypeScript as well as the Angular Style Guide conventions.

Finally, this template configures unit testing with Karma and Jasmine integrated with webpack. It also includes end-to-end (E2E) tests using Protractor. These configurations alone can save you a dozen hours versus configuring yourself.

Gotchas

Certainly check out the README file for this project. It has a lot of great information on how to use Angular with or without this template and highlights areas where you may otherwise stumble. One other word of caution – this template leans on the bleeding edge so you may find some instability along the way. The maintainer so far seems to do a nice job keeping up with any logged issues.

Bottom Line

This is a must-see and must-watch starter template for ASP.NET developers using Angular. There is nothing more to say, take a look for yourself.

Final Thoughts

The Angular and ASP.NET frameworks are both evolving at a rapid pace and it can be difficult to keep current with the changes. These templates can help you start coding quickly and help you incorporate new technologies and patterns as they are published.

These are two of the best and more noteworthy starter templates for Angular and ASP.NET. Give them a try and share your thoughts below. If there are any other starter templates you find helpful, please let everyone know in the comments.

SystemJS to Webpack – Before You Begin

SystemJS to Webpack - Before You Begin Title

This is a primer discussing why to move from SystemJS to webpack in your Angular project. The post also describes some of the hurdles you may run into with this effort.

While it doesn't go into specific webpack configuration, this article aims to provide an overview for someone who has heard of webpack but doesn't quite understand why or how to get started. Specific details configuring webpack with ASP.NET Core are coming in future posts.

SystemJS – Starting Point

There are several posts on this blog with examples using SystemJS to mimic Node.js module resolution in the browser. While TypeScript understands how to resolve types by npm package name during development, SystemJS fills this need in the browser by mapping package names to specific script files within the npm packages. This is an effective and minimal way to setup an Angular 2 application to load its dependencies from npm and get going quickly.

After starting with SystemJS, applications (even small ones) quickly grow to contain hundreds of ES2015 modules that are then downloaded by the browser to execute the application. This is probably not a problem during development when the browser and the server are on the same machine.

At some point, however, you may want to host your application for others to see. The performance hit of loading this many modules becomes noticeable. This situation leads to creating some type of build combining these hundreds of requests into only a handful.

Whereas SystemJS manipulates the browser to understand node module resolution, webpack (and similar build tools) manipulate the code to accommodate the browser's needs. Whether SystemJS or webpack, you continue to code the way that makes you the most productive with as many ES2015 modules in as many files as make you happy. Unlike SystemJS, webpack provides the browser with a streamlined payload to load the application as efficiently as possible.

Destination Webpack

Webpack at its core is a JavaScript module bundler meaning it takes JavaScript modules from separate files and combines them into one file. Webpack can be extended, though, by using loaders which allow you to bundle other types of files. So, while webpack doesn't understand TypeScript natively, it processes .ts files by using a loader.

Webpack has another extensibility mechanism called plugins. Where loaders handle specific file types, plugins process the contents of the loaded files. Plugins, for example, are responsible for minifying code where variable names are shortened and whitespace is removed.

One aspect of webpack that is different from a tool such as grunt or gulp is that it is more declarative meaning you configure an object literal and that object defines what should happen when you run the webpack command. The declarative nature of webpack ideally requires less configuration code and should lead you into a build that is more optimized than if you had to wire the pieces up yourself.

There are two other npm packages that carry the webpack name but are not the bundler, itself. These packages work with the bundler to improve the development experience. They are webpack-dev-server and webpack-dev-middleware.

The webpack-dev-server npm package is a lightweight development server based on Node.js and Express. It has all the basic development server features and includes hot module replacement. Hot module replacement (HMR) is a process where the development server uses a WebSocket connection to replace the code of a given module in the browser when it has changed in the development environment. This does not require a full page refresh to reflect the updates making it seamless to view your changes in the browser during development.

The webpack-dev-middleware npm package is a little more esoteric. It runs as an in-memory store containing the build output as opposed to writing the output to disk. This can decrease the time between when you modify a file and when you can see the changes running in the browser.

Configuration Troubles

Currently in early 2017, webpack is moving from version 1 to version 2. This can lead to incompatibilities in the webpack tool chain. When configuring a webpack build yourself, expect to find out-of-date examples and see errors processing your build.

Not all loaders and plugins support both webpack 1 or webpack 2 and you may find yourself trying different versions of these npm packages with different versions of webpack. Throw in the fact that TypeScript is adding significant new features through all of this and it's a recipe for configuration troubles.

This isn't meant to scare you off, just be prepared. Expect to search through the GitHub issues of some of these frameworks looking for answers or expect to post issues yourself. It's not always clear which combination of settings are correct but the webpack community is by-and-large responsive and committed to this tooling.

This is an example of an issue you may find. While the TypeScript compiler allows comments in the tsconfig.json file as of version 1.8, some of the TypeScript webpack loaders will blow up if there are comments in this file. There is no helpful error message, it just throws an error that a property is not defined on a null reference.

It's likely these issues are resolved over time, but you should understand what you are up against.

Replacing SystemJS

Now that you know about webpack's advantages and potential pitfalls, what are the general steps required to replace SystemJS? This is a summary:

  • Move polyfill scripts from index.html into the webpack bundle
  • Compile and bundle the TypeScript files
  • Move any external component HTML templates and stylesheets inline
  • Add a reference to index.html for the new bundled resource

Move polyfill scripts from index.html into the webpack bundle

Many Angular tutorials instruct you to put polyfill dependencies directly in the index.html (or alternatively named default HTML) file. This approach works and will continue to work with webpack but you should consider moving these dependencies into the webpack configuration.

First, including these dependencies into a bundled request improves performance. Second, having all your script dependencies in one place decreases the time to find a given dependency – thus increasing maintainability. Third, webpack resolves dependencies through node module resolution meaning you add the package name to the configuration and you're done. Using SystemJS, you often must identify the correct script to load from within the npm package.

Compile and bundle the TypeScript files

While you could continue to compile TypeScript with the TypeScript compiler, the idea is to move everything into webpack. There are several loaders that handle TypeScript files and are generally straightforward to configure. A popular TypeScript loader in the Angular community now appears to be awesome-typescript-loader.

Move external component HTML templates and stylesheets inline

This one is Angular-specific. When you have components with external templates and/or stylesheets, Angular loads these files as separate requests. By using a loader like the angular2-template-loader, the build now can combine the contents of the external templates and stylesheets into the component script itself.

Note: Understand that by moving the templates and stylesheets inline, setting the @Component directive's moduleId property is unnecessary. Leaving the moduleId property set in the component can lead to issues. While the available tooling should most likely handle this, you may find you must account for this yourself by removing the settings manually or creating automation.

Add a reference to index.html for the new bundled resource

Finally, once you define the file(s) that webpack outputs, you must reference the new bundled file(s) in your main HTML file. As you may have guessed, there are even webpack plugins to handle this as well based off the webpack configuration (see html-webpack-plugin).

Additional Configuration

While the previous sections listed the necessary pieces of a basic webpack build. You have so many more options available to you to optimize your code. Some build steps to consider are: Ahead-of-time (AOT) compilation, using the wwwroot folder in ASP.NET Core, tree-shaking, running tests, and using the webpack development server with hot module replacement.

Tackling the Beast

So, you still want to get going with webpack? Where do you begin? There are many projects on Github and other sites that provide insight into how this tool works. It appears to still be hit or miss as far as quality. Looking at it from an ASP.NET developer's perspective, the guidance options are fewer. With that said, here are some links to get started:

None of these resources paint the full picture but they provide a good overview. In addition to these general resources, visit the documentation for the individual loaders and plugins to get details regarding compatibility with other packages.

You should consider creating your own webpack build from scratch. There are advantages to doing it this way. If you like knowing how these tools work, this is a rewarding way to learn, albeit a time-intensive one.

Focus on one piece of the build at a time. It's easier to identify which pieces of the build are failing and you can more easily investigate or replace that specific loader or plugin to compare results. Once you stabilize one part, move on to the next until you have the build that you want.

Start with the pieces outlined in the Replacing SystemJS section and continue from there.

More on the Way

You've learned why you should consider moving to webpack and the general approach to creating a webpack-based build. Again, this is just a primer. The plan is to ultimately provide you with a webpack configuration that works well with Angular and with ASP.NET Core. You will see more posts about webpack here soon.

For now, what are your favorite webpack resources? Did you build a template that others may find useful? Please share in the comments.

Code Camp NYC 2015 Talks

Code Camp NYC 2015

I had the pleasure of giving two talks at Code Camp NYC 2015. It was a great experience and I met many smart and dedicated developers. Here are the talks’ descriptions, slides, and source repositories. I will explore these topics more on the blog in the weeks to come.

Intro to JavaScript Modules

If you are a web developer, you have encountered JavaScript modules and hopefully you are using them. But if you aren’t or you think you can be using them better, this talk will give you the lay of the land for using JavaScript modules effectively. You’ll learn about the most common players like CommonJS, AMD, SytemJS and how they relate to the EcmaScript 6 standard. In addition, you’ll understand how to use tooling for combining and loading modules. There are many options and the choices can be overwhelming. By the end of this talk, you’ll know which technologies and frameworks can help to incorporate better JavaScript modules in your code.

Examples on GitHub

Angular 2 Tooling Today with Visual Studio

Angular 2 is the next evolution in Angular and along with the framework comes a recommended set of tools to increase developer productivity. Whether or not you are ready for Angular 2, you can start using these tools now with your current Angular projects. Attendees should have a basic understanding of Angular 1.x concepts. This talk demonstrates the fundamentals for using tools and frameworks such as TypeScript, SystemJS, and EcmaScript 6 in an Angular 1.x application. Armed with this knowledge, you can prepare for migrating to Angular 2 and more importantly improve your developer workflow today!

Example on GitHub

Angular Filters

Angular Filters

Angular filters are a convenient and simple way to format data in your application. Oftentimes, the values you use in code are not formatted for your users’ eyes. Whether they are currency values or dates, you need to process this data into a human-readable format.

Angular filters excel at formatting data. They are also used to process arrays to display collections of UI elements sorted, filtered, or paged. They are very powerful and with much power comes great responsibility.

This post covers what filters are, how they work, and general guidance to use them. For specific usage instruction for the built-in filters, the Angular docs do a very good job. Now it’s time to look at the basics.

Filter Basics

For those that didn’t read the last post on expressions, filters process the result of an expression before it is rendered. A simple example is formatting a number as currency.

Filter scenarios are generally simple input and output, but filters also accept parameters. In the case of formatting a currency, the built-in currency filter accepts a string parameter to change the currency symbol as well as a parameter to denote how many decimal places to display.

The syntax for filters is straightforward. After the expression you wish to filter, use the pipe character | to declare the filter. To set parameters, follow the filter name with a colon : and add the parameter value. Each subsequent parameter value is separated by a colon :. Using the built-in currency filter looks like this:

{{ vm.number | currency : '€' : 0 }}

The default currency filter displays the input with a currency symbol, commas to separate the thousand and million places, and also rounds the value to two decimal places. This example uses two parameters to change the currency symbol and to remove the decimals entirely.

In addition to the formatting advantages, the currency filter also rounds the decimal places. For instance using the above example, the value 999.9 displays €1,000 whereas 999.4 displays €999 – nice!

When using parameters, the order is important. For instance, if you want to leave the default currency symbol but also want to limit the decimal places to 0, you still have to pass the symbol as a parameter.

Another nice feature is chaining. You can chain multiple filters to format a single value. For instance if you want a date format with all uppercase letters, you can use two filters together.

{{ vm.date | date : 'MMMM d, yyyy' | uppercase }}

It’s important to note that the order matters. Processing flows from the leftmost filter to the right and subsequent filters can overwrite the processing done by a previous filter.

Preprocess Filters for Performance

When using a filter within a binding expression, it is loaded in the DOM. While the syntax is convenient, the performance implications can add up. To get a better understanding of how filters and expressions affect UI performance, read Todd Motto’s post on Angular performance. The important thing to remember is that anytime you add a piece of Angular code to your markup, you are adding processing to the $digest cycle. This $digest cycle runs repeatedly whenever a binding is changed in the UI and the amount of processing can easily increase by an order of magnitude depending on how you choose to write your expressions, bindings, directives, and filters.

For this reason, consider using filters within a controller or service of your application where it runs outside of the scope of the DOM and on-demand when needed instead of linked to the $digest cycle. Use the built-in $filter service to call a filter from a controller or service.

vm.preprocessCurrency = $filter('currency')(vm.number, '€', 0);

In this example, vm is the scope object in the controller. The $filter service is injected as a parameter to the controller function. If you understand how to use a filter in markup, using the $filter service in the controller is similar. First, pass the filter name as a string to the $filter service. Invoking this service returns the filter function which is why it is followed by a second invocation to process the data. The filter function’s first parameter is the data to filter, vm.number, followed by any other parameters. In this case, the currency symbol and the amount of decimal places are passed to the filter function.

This plunker demonstrates the two different filter approaches in action.

Anatomy of Custom Filters

Under the covers, filters are relatively simple JavaScript objects. Similar to other Angular objects, they are created with the angular.Module object.

angular
    .module('app', [])
    .filter('kittens', function () {

        return function (data, exclamations) {

            var kittens = 'Ooh, Kittens';
            exclamations = typeof exclamations !== 'number' ? 1 : exclamations;

            for (var i = 0; i < exclamations; i++) {
                kittens = kittens + '!';
            }

            return kittens;
        };
    });

The kittens filter converts any input into the value Ooh, Kittens! with an optional parameter to set the number of exclamation points (admittedly, probably only useful for this post). This is an example using the filter in markup.

{{ vm.someValue | kittens : 5 }}

To create the filter, use the module’s filter method which accepts a string representing the filter name as the first argument and a factory function as the second argument. The filter name must be a valid expression identifier and cannot contain any special characters, periods ., or hyphens -.

The factory function is a function that returns a new instance of the filter function. Because filters should be stateless, the factory function helps to ensure that output values are consistent, otherwise wreaking havoc on the $digest cycle. The factory function can also accept other dependencies as arguments.

This plunker demonstrates the custom filter.

Filtering it Down

Angular filters are a convenient and simple feature of the Angular framework. They help you format and process data in the view. They are flexible in that you can use them within controllers or services to preprocess data. And, you can write your own custom filters to re-use throughout your application.

Again, be sure to check out how to use the built-in filters in the Angular documentation. If there’s anything else you wanted to know about filters, please leave a comment. This post was created because an interested reader left a comment. Thanks Mariusz for the idea.

Angular Expressions

Angular Expressions Header

One of the first things a developer writes in Angular, other than the ng-app directive, is an expression. This is easily identified as the code written inside of a binding {{ }} or directive.

<input type="text" ng-model="name" />
{{'Hello ' + name + '!'}}

In this example, 'Hello ' + name + '!' is the expression. The official Angular documentation is pretty clear (maybe it wasn’t clear in earlier versions) that bindings and expressions are distinct items. However, there are (highly-ranked) places on the internet listed in search results that don’t always acknowledge the difference so readers beware. While you naturally find expressions and bindings together, they are not the same. This post is dedicated to explaining how expressions serve a broad and important role in the Angular framework beyond just data binding.

Expressions in a Nutshell

A better way to summarize Angular expressions is that they are a way to write JavaScript in HTML. Writing JavaScript in HTML? If you immediately cringe when reading that, it’s OK. You probably have been taught that you shouldn’t write JavaScript in your HTML because JavaScript is for functionality and HTML is for structure and you want to keep those concerns separate. Separation of concerns is still important when using expressions and thankfully Angular allows only a subset of JavaScript expressions in an HTML view.

The key differentiator of an Angular expression is that it is executed in an encapsulated scope. This means you don’t have to worry about global objects conflicting as you normally would writing JavaScript in HTML. In general, the scope in which an Angular expression runs is defined by a controller. If no controller is present, expressions execute against a default scope.

Also, expressions are converted to JavaScript functions using Angular’s $parse service. The $parse service provides many benefits and enforces certain limitations that you should understand.

Limitations or Separations of Concern

Angular expressions have limitations when compared to standard JavaScript. The limitations, however, are reasonable when you consider the role expressions play in the overall Angular framework.

There is no access to global variables or objects in Angular expressions meaning there is no access to the document or the window objects directly. To access these objects, use the testable $document and $window wrappers in your controller. Scott Allen has a good example illustrating this functionality.

Also, no control flow is allowed in an expression, meaning that you cannot use conditional logic (including ternary expressions), loops, or exceptions. You also cannot declare functions within an expression and you cannot use the comma or void operators.

There are also some limitations around which operators are supported. Even when they are supported, they may not work as you would expect. For instance while {{ 1 + 1 }} displays 2, if one of those values comes from a text input, the values will concatenate a string 11. Futher, the ++ operator is not allowed. Comparison operators such as >, <=, and == generally work as expected but you can save yourself some headache by moving this logic into a function on the controller.

Here are two expression examples. The first example demonstrates what is possible with expressions. The second example shows how to move the logic into a controller.

Powerful Expression Example

<!DOCTYPE html>
<html ng-app>
<head>
    <title>Dining Calculator</title>
</head>
<body>
    <input type="number" ng-model="totalBill" placeholder="Total Bill" />
    <input type="number" ng-model="tipPercent" placeholder="Tip Percentage" />
    <input type="number" ng-model="peopleAmt" placeholder="Amount of People" />
    <div>{{((totalBill + totalBill * tipPercent/100) / peopleAmt) || 'Calculating...'}}</div>
    <script src="Scripts/angular.min.js"></script>
</body>
</html>

Using a Controller

<!DOCTYPE html>
<html ng-app="app">
<head>
    <title></title>
</head>
<body ng-controller="Main as vm">
    <input type="number" ng-model="vm.totalBill" ng-change="vm.calculateTotal()" placeholder="Total Bill" />
    <input type="number" ng-model="vm.tipPercent" ng-change="vm.calculateTotal()" placeholder="Tip Percentage" />
    <input type="number" ng-model="vm.peopleAmt" ng-change="vm.calculateTotal()" placeholder="Amount of People" />
    <div>{{vm.totalPerPerson}}</div>
    <script src="Scripts/angular.min.js"></script>
    <script>
        (function () {
            'use strict';

            angular.module('app', [])
                .controller('Main', main);                

            function main() {
                var vm = this,
                    CALCULATING_MSG = 'Calculating...';

                vm.calculateTotal = function () {
                    var totalPlusTip = vm.totalBill + vm.totalBill * vm.tipPercent / 100;
                    var amtPerPerson = totalPlusTip / vm.peopleAmt;

                    vm.totalPerPerson = amtPerPerson || CALCULATING_MSG;
                }

                vm.calculateTotal();

                return vm;
            }
        })();
    </script>
</body>
</html>

You’ll see in the first example that the expression used is quite powerful. There is a fair amount of math involved and it can even check for the falsy value NaN in order to show valuable information to the user.

The controller example at first glance is significantly more code than the first. Looks can be deceiving, however. Once required to apply any validation or formatting to the first example, the expression won’t hold up because it requires the introduction of control flow into the logic – which is not allowed in Angular expressions.

Another key difference is found when looking at only the HTML markup. Even though there is more HTML markup in the controller example, it reads easier because the function names label what the expression does. In addition, debugging the logic in the controller example is easier.

Again, the generally appropriate way to handle Angular expression limitations is to keep logic out of HTML views and instead move it into controllers or services. The limitations help to nudge you into writing cleaner, more maintainable code.

Benefits

In the previous section, you saw how expressions offer a subset of JavaScript in HTML. Angular expressions also offer many benefits above and beyond what JavaScript typically provides including graceful handling of null and undefined, use with directives, and filters.

One area where Angular expressions shine is in their ability to gracefully handle null and undefined values. Here is an example of code that would cause problems with traditional JavaScript UI code.

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <span id="dSpan"></span>
    <script>
        (function () {
            'use strict';

            var vm = {};
            dSpan.innerHTML = vm.foo;

        })();        
    </script>
</body>
</html>

When this code executes, the UI displays the word undefined. While having an undefined property in code is less than ideal, the user doesn’t need to see this. Further, if you expand the statement to dSpan.innerHTML = vm.foo.bar;, your application will throw a TypeError bringing your JavaScript execution to a grinding halt.

Here is an example of using an Angular expression for the same purpose.

<html ng-app="app">
<head>
    <title></title>
</head>
<body ng-controller="Main as vm">
    <span>{{vm.foo}}</span>
    <script src="Scripts/angular.min.js"></script>
    <script>
        (function () {
            'use strict';

            angular.module('app', [])
                .controller('Main', main);                

            function main() {
                var vm = this;
            }
        })();
    </script>
</body>
</html>

Run this in the browser and you see that the UI shows nothing for the undefined property. Change the expression to vm.foo.bar and even the TypeError exception is ignored. Convenient, indeed.

Angular expressions are one of the primary inputs for bindings and directives. This is part of the magic of Angular in the UI. The syntax is clean and generally easy to follow between the view and the controller. In addition to the binding examples already shown, many if not most built-in Angular directives take an expression as input.

<div ng-bind="expression"></div>
<div ng-class="expression"></div>
<div ng-click="expression"></div>
<div ng-focus="expression"></div>
<div ng-if="expression"></div>
<div ng-mousedown="expression"></div>
<!-- and many more...-->

Finally, expressions have a nifty feature called filters. Filters are a way to format the result of an expression for use in the UI. For example if an expression returns a number, the filter is responsible for formatting this number as currency before displaying it in the UI.

Filters are denoted using a pipe character | to the right of an expression followed by the filter name and parameters separated by colons. You can create your own custom filters. Here is a built-in filter example for currency formatting which displays the value $5,147.47.

{{ 12 + 5135.467 | currency:$:2}}

In Closing

This is just a peek into the world of Angular expressions – a feature used by all and misunderstood by many. They give Angular the syntactic ease upon which the framework loosely couples views to controllers.

Angular expressions are deceptively simple, purposefully limit their abuse, and offer delightful benefits to you, the developer. So the next time you open up those double curly braces or the first quote of an ng-bind attribute, write that expression with purpose and care.

Client-Side Productivity with Browser Link

Browser Link Banner

As you know Angular is a client-side framework – it’s home is in the browser. Visual Studio, on the other hand, has traditionally shined as the server development environment. Well there is a technology that attempts to bridge the gap between Visual Studio and the browser – it’s called Browser Link.

This post details Browser Link’s best features and discusses why you should use it. You will learn how to set it up when using static files for your Angular project and you will be prepared for some limitations and trade offs you may encounter. Overall you will find that Browser Link is a compelling and under-utilized tool in Visual Studio that you should add to your tool belt.

What is Browser Link?

Browser Link is a feature introduced with Visual Studio 2013 that runs when you press F5 to build, deploy, and run your project. It leverages the two-way communication of SignalR to send information from Visual Studio to the client and back.

While Visual Studio-to-client communication may seem trivial, this is a rich canvas on which to build truly time-saving features. For instance, think about how much time you spend in the browser’s F12 developer tools. What if you can link the work that you do in these tools to the code in Visual Studio? How many times do you duplicate CSS changes that you make in the browser by copying them to the correct file in Visual Studio? Browser Link makes this type of workflow obsolete by communicating changes between both the client-side and server-side development environments.

Setting Up Browser Link

There isn’t much to know to setup Browser Link. The two main requirements are that Browser Link is enabled and the project is running in debug mode. To enable Browser Link, press the Browser Link button’s drop-down arrow and press Enable Browser Link.

Enable Browser Link

Unless configured otherwise, debug mode is enabled by default when you run your project with F5. However to ensure you are running in debug mode, select Start Debugging in Visual Studio’s Debug menu.

Because many Angular applications use static HTML files instead of .cshtml or .aspx files, there is one additional configuration that needs to be added to the web.config file to enable Browser Link with static HTML files:

<system.webServer>
    <handlers>
        <add name="Browser Link for HTML" path="*.html" verb="*"
            type="System.Web.StaticFileHandler, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
            resourceType="File" preCondition="integratedMode" />
    </handlers>
</system.webServer>

For more on enabling Browser Link, read the corresponding ASP.NET documentation.

Finally, you should download and install the Web Essentials Visual Studio extension. The download and installation instructions are on the Web Essentials website.

Browser Refresh

The basic Browser Link scenario is Browser Refresh. This feature comes out-of-the-box and allows you to trigger the browser to refresh from Visual Studio. For example, you make a change to your client-side code in Visual Studio. Then for anything that doesn’t require a recompile, you would typically go to your browser and refresh the page in order to verify your changes. With Browser Link running however, you simply press the Browser Link refresh button or use the CTRL + ALT + ENTER key combination to save your files and simultaneously trigger the browser to refresh right from within Visual Studio.

Because Browser Link uses web standards, this works with any browser including mobile browsers on devices and in emulators. You can also trigger multiple browsers. If you want to check that your CSS animation runs across all of your application’s supported browsers, one button press or key combination refreshes all of them at the same time.

Web Essentials and Browser Link

Some of the most interesting Browser Link uses are found in the popular Visual Studio add-in Web Essentials. Web Essentials is a sweeping collection of tools. You should take a look for yourself when you have the chance – it’s good stuff. There are several features to discuss related to Browser Link.

Once you have installed the Web Essentials add-in and enabled Browser Link, there is a new Web Essentials toolbar that appears at the bottom of the page in your browser when you run your Visual Studio project.

Browser Link toolbar

This toolbar is displayed or hidden using the CTRL key. The toolbar provides several interesting pieces of functionality including two of the most useful: Save F12 changes and Inspect.

Have you ever spent time adjusting the CSS properties of an element in the browser to get just the right position, font size, or layout? The typical workflow is often then to copy the changes you made, if you remember them, into Visual Studio, save the files, and then refresh the browser to double check that you copied the CSS correctly. By using the Save F12 changes button, Web Essentials uses Browser Link to send the DOM changes back to Visual Studio and add them to the correct CSS selector in the correct file – it’s almost like magic.

Another feature is an easier way to find the source code for browser elements. In the past you may have found an element in the browser’s developer tools and then searched your project for the element’s id or class. Now, you can press the Inspect button on the Web Essentials toolbar to enable inspection mode. Once this mode is enabled, click on the element you are interested in and Visual Studio jumps to that markup in the appropriate code file – again, almost like magic.

Pro tip: hover over the buttons in the Web Essentials toolbar to see its keyboard shortcut.

Limitations and Trade-Offs

While the Browser Link technology enables some very useful scenarios, you should be aware of some issues that you may see. First, you are limited in Visual Studio by debug mode. Things like renaming or moving files can’t be done while running in this mode. Also, Browser Link sends a lot of network traffic so if you are using the browser’s network profiler, you may want to shut Browser Link off temporarily.

Furthermore, Web Essentials is often a proving ground for functionality before moving it into Visual Studio. You may encounter some functionality that doesn’t quite work as you expected. The key here is to try out the tooling on a non-critical project first to develop a comfort level and/or be sure to use source control or make a backup of your project. I use the features detailed in this post and find them to be stable and helpful. If for some reason the tooling doesn’t produce the output you were expecting, using CTRL+Z in Visual Studio to undo the recent changes typically works – but not always.

In Summary

Browser Link is a great Visual Studio feature for web developers. It helps to bridge the divide between development environment and browser tools to increase your productivity. It’s easy to setup and provides compelling features such as Browser Refresh, Save F12 changes, and Inspect. Regardless of whether you are using Angular or other web frameworks, you should give it a try.

The next post will dive into one of the first Angular features that developers use – expressions. They are included in practically every ‘Hello World’ Angular demo and it is important to understand what they are and what their role is in an Angular application – see you then!

Your First Angular Project in Visual Studio

angular-visual-studio

Today is the day. You have been hearing about Angular for a long time now. You have listened to the podcasts, you’ve watched the videos, and you have followed the pre-canned tutorials. Now you are creating your own project. Maybe you have an application idea or you plan to work your way through the documentation. You open up Visual Studio and pause. Which type of project template should you use? What type of back-end should you setup? So many questions.

This post looks to simplify the process and walks through a basic project structure in Visual Studio designed for quick setup and a solid foundation for separation of concerns. The structure aims for simplicity yet some of the recommendations may not be intuitive for the average ASP.NET developer. Angular is a client-side framework and therefore much of the ceremony performed to use ASP.NET for server-side development is unnecessary.

This walk through is for Visual Studio 2013. If you don’t have it, download the community edition (it’s FREE) and get the latest updates. Also install the Web Essentials extension to get the latest web development tooling for Visual Studio. If you have seen Visual Studio 2015, it introduces a new project structure that aids with client-side development. Even though this project structure is aimed at Visual Studio 2013, it should make it is easy to migrate to Visual Studio 2015 when the time comes.

Also, this post doesn’t cover build tools for bundling, minification, and testing even though Visual Studio supports these scenarios. Look for posts on these topics in the future.

Choosing the Project Template

This walkthrough uses a web application project as opposed to a web site project. This is part personal preference and part pragmatism. If you are significantly more comfortable with web site projects, go head and use them. It doesn’t make a significant difference for the purpose of this post.

Using a web application project is not straightforward, however. The tricky part is how the default templates setup things you don’t need – mainly everything specific to ASP.NET.

In the world of client-side frameworks, there is a much cleaner separation of client and server. There is generally no need to create .aspx or .cshtml files in order to render views on the server. Much of the rendering logic in these files can be done in Angular with static HTML files. There may be reasons to use server-rendered views for specific scenarios but start out considering that you don’t need server-rendered views.

“But what about data?” you say. Start out by using static .json files on the file system or hard code collections in your JavaScript. If you need to persist data, there are various in-browser technologies to save what you have done. Eventually yes, you will need to create a back-end but not for starting a basic Angular project.

Now it’s time to create the project. Go ahead and create an ASP.NET Web Application project.

create-first-vs-project

Press OK and this brings you to the dialog where you choose a template and select the features for your application. Choose the Empty template and uncheck all of the ASP.NET features.

create-empty-vs-project

Press OK to create the project. You see the project is indeed empty.

empty-structure

If you press F5 to run the project, you will get a 403 Forbidden error from IIS because there is nothing for you to access.

There is no need for server-side controllers, views or routes at this time. To start, add an index.html file to the root of your project, type Hello World in the body, hit F5 and you will see your friendly message in the browser.

Adding Angular

In order to write an Angular app, you need to reference the Angular JavaScript library. You can go to the Angular website and download it or reference it from the CDN (content delivery network). However, Visual Studio has the NuGet package manager to easily download the scripts and add it to your solution.

Note: in Visual Studio 2015, client-side dependencies will typically be loaded via client-side package managers as opposed to NuGet.

To load the Angular scripts from NuGet, right click on the solution and select ‘Manage NuGet Packages for Solution…’ from the dropdown. This displays the NuGet dialog. Search for “angularjs” and find the listing for AngularJS Core. There are other packages but this one provides the base Angular framework from the AngularJS Team (so it says). Click Install, select your web project, click OK, then Close to exit the dialogs and NuGet adds the Angular script files to your solution.

nuget-script-folder

Now create a script tag to reference the Angular script in your index.html file.

<script src="Scripts/angular.min.js"></script>

Creating a Basic Angular App Structure

Much of what is recommended here comes from John Papa’s information in this blog post and in his style guide. If you are going beyond this basic structure, reading the source material will give you tips to scale your application architecture.

First, start by adding an app folder to the root of your web project. Within the app folder, add two files: app.module.js and main.js.

The app.module.js file houses a single application-level module for your application. In this example, your application has an application-level module that loads the other modules of the application. The purpose of adding app.module.js as a separate file is to introduce the concept that modules, controllers, services, directives, views, etc. should be defined in their own files. Of course this is negotiable but it’s a good place to start. The contents of the app.module.js file should have the following contents.

(function() {
    'use strict';

    angular.module('app', []);

})();

This example uses an IIFE (immediately-invoked function expression) to immediately execute this code and also to encapsulate its scope. This pattern is used with every module. Also, notice the use of 'use strict'. This triggers modern browsers to run the JavaScript in strict mode. It is optional but it can help you avoid coding problems and many linters such as JSLint complain when it’s not included. The call to angular.module registers the module with the Angular framework.

In the main.js file, create a controller. In John Papa’s blog post, controllers do not use the word ‘controller’ in the file name. At first, I thought this was to save keystrokes, but he makes a good point about how this works with routing. However, there are numerous instances in Angular tutorials where ‘controller’ or ‘ctrl’ are used in the naming (including in John Papa’s style guide) so make the best decision for your projects – just be consistent. Here is the code for the main controller.

(function () {
    'use strict';

    angular
        .module('app')
        .controller('Main', main);

    function main() {
        var vm = this;
        vm.food = 'pizza';
    }

})();

In this IIFE, the controller is registered with the app module. An argument could be made to create a main module with which to associate the controller but being that this is the only controller in the project, this can be left out. Once the project grows in complexity, you should consider registering the controllers with feature-level or section-level modules and leave the application-level app module for registering these various sub-modules (read more in the style guide).

The function main is the controller itself. This controller is configured to use the controllerAs syntax. Again, John Papa details the benefits in his style guide. From the perspective of writing the controller, the big notable is that the properties and methods that you apply to scope are defined on this instead of an injected $scope parameter. Most examples I have seen online for Angular use $scope so this may be new to you. In addition, notice the use of the variable vm to capture the scope. This practice helps to avoid any confusion if/when you define nested functions also using the this keyword.

Finally, take a look at the index.html view. Here is the code.

<!DOCTYPE html>

<html ng-app="app">
<head>
    <title></title>
</head>
<body ng-controller="Main as vm">

    <input type="text" ng-model="vm.food" placeholder="Enter food" />

    <p>Sriracha sauce is great with {{vm.food}}!</p>

    <script src="Scripts/angular.min.js"></script>
    <script src="app/app.module.js"></script>
    <script src="app/main.js"></script>

</body>
</html>

First you see the ng-app directive set to the app module to bootstrap the application. On the body tag you see the use of the controller as syntax in the view. Something to note, the use of the name vm in the view has no correlation to its use in the controller. The two variables can have different names. Next, you see the basic example of using the vm scope with a simple input scenario where the value of the input is bound to the expression vm.food. Finally, all of the scripts are referenced on the page.

After completing these steps, your application structure looks like the following.

final-structure

When you run the application you should be able to pair your favorite food with the infamous Rooster Sauce.

final-interface

Conclusion

To those of you who have been using the full breadth of ASP.NET over the years, using static HTML files may seem like a foreign concept and admittedly the ASP.NET project templates tend to favor server-side views.

However, now you have a project that feels like other ASP.NET projects you have worked on. You are still pressing F5 to startup IIS Express and the HTML and JavaScript editors are the ones that you are used to using.

You also have a starter Angular application with basic separation of concerns. You even have a naming convention to use for your modules and controllers as well.

If you would like to download the finished project, you can do so on GitHub.

In the next post, you will learn about a Visual Studio tool called Browser Link. It provides useful features especially for client-side development but there are some tricks to setting it up with static files. Until then, enjoy experimenting with your new Angular project.