Click here to Skip to main content
15,879,095 members
Articles / Web Development / ASP.NET
Tip/Trick

Setting up Angular 2 in ASP.NET Core using Webpack

Rate me:
Please Sign up or sign in to vote.
4.38/5 (4 votes)
23 Jul 2017CPOL3 min read 14.3K   4   2
In this tip, we can see how to set up Angular 2 application in ASP.NET core using webpack, a JavaScript library, so that we can start focusing on writing Angular features rather than spending time in setting up an environment to run.

Introduction

This article will help you to configure Angular 2 in ASP.NET core which is a tedious task to do. It mainly focuses on configuring the Angular 2 using webpack with very minimal configuration steps right from installing node to running app from Visual Studio 2015.

Background

Earlier, to configure Angular 2, we needed so many files like package.json, tsconfig.json, typings.json, system.config.json and deploying all these was a question mark. The intention of this article is to make things simpler by using webpack which bundles all the configurations in a single large chunk that prevents web pages from accessing various third party resources through URL whenever they are loaded in the browser.

Using the Code

  1. Install Visual Studio 2015 community edition.
  2. Install .NET core preview tools from https://www.microsoft.com/net/download/core
  3. Install node js from https://nodejs.org/en/
  4. Install typescript from https://www.microsoft.com/en-us/download/confirmation.aspx?id=48593

After installing the above, open node command prompt, then execute the below commands:

  1. "npm install npm@latest" to upgrade to the latest version of NPM
  2. "npm install -g typescript" to install typescript globally
  3. "npm install -g typings" to install typings globally

Create a new project by selecting ASP.NET Core web application and select empty from the available templates. After the project is loaded, add the below line in project.json file.

JavaScript
"Microsoft.AspNetCore.StaticFiles": "1.0.0"

After this, add the two below lines in the startup.cs file by commenting the default code.

C#
//app.Run(async (context) =>
//{
//    await context.Response.WriteAsync("Hello World!");
//});
app.UseDefaultFiles();
app.UseStaticFiles();

The next step is to add package.json file to the project with code below, Visual Studio automatically restores all the libraries mentioned in the file when it is saved, if not, right click on "dependencies" and click "restore packages" or run "npm install" from node js command prompt by browsing through project directory in the node js command prompt.

JavaScript
{
  "name": "asp.net-angular2-webpack",
  "version": "1.0.0",
  "description": "A webpack starter for Angular",
  "scripts": {
    "start": "webpack-dev-server --inline --progress --port 8080",
    "test": "karma start",
    "build": "rimraf dist && webpack 
    --config webpack.config.js --progress --profile --bail",
    "webpack": "webpack"
  },
  "license": "MIT",
  "dependencies": {
    "@angular/common": "~4.2.0",
    "@angular/compiler": "~4.2.0",
    "@angular/core": "~4.2.0",
    "@angular/forms": "~4.2.0",
    "@angular/http": "~4.2.0",
    "@angular/platform-browser": "~4.2.0",
    "@angular/platform-browser-dynamic": "~4.2.0",
    "@angular/router": "~4.2.0",
    "core-js": "^2.4.1",
    "rxjs": "5.0.1",
    "zone.js": "^0.8.4"
  },
  "devDependencies": {
    "@types/node": "^6.0.45",
    "@types/jasmine": "2.5.36",
    "@types/source-map": "0.1.26",
    "@types/uglify-js": "2.0.27",
    "@types/webpack": "1.12.29",
    "angular2-template-loader": "^0.6.0",
    "awesome-typescript-loader": "^3.0.4",
    "css-loader": "^0.26.1",
    "plug in": "2.0.0-beta.5",
    "file-loader": "^0.9.0",
    "html-loader": "^0.4.3",
    "plug in": "^2.16.1",
    "jasmine-core": "^2.4.1",
    "karma": "^1.2.0",
    "karma-chrome-launcher": "^2.0.0",
    "karma-jasmine": "^1.0.2",
    "karma-sourcemap-loader": "^0.3.7",
    "karma-webpack": "^2.0.1",
    "null-loader": "^0.1.1",
    "raw-loader": "^0.5.1",
    "rimraf": "^2.5.2",
    "style-loader": "^0.13.1",
    "typescript": "~2.3.1",
    "webpack": "2.2.1",
    "webpack-dev-server": "2.4.1",
    "webpack-merge": "^3.0.0"
  }
}

Then add tsconfig.json to the project with the code as below:

JavaScript
{
  "compileOnSave": true,
  "compilerOptions": {
    "noImplicitAny": false,
    "noEmitOnError": true,
    "removeComments": false,
    "sourceMap": true,
    "target": "es5",
    "module": "commonjs",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [ "es6", "dom" ],    
    "moduleResolution": "node",
    "outDir": "wwwroot/dist",
    "sourceRoot": "wwwroot/app",
    "types": [ "node", "source-map", "uglify-js", "webpack" ],
    "noStrictGenericChecks": true
  },
  
  "exclude": [
    "node_modules",    
    "dist"
  ]
} 

The very next step is to add webpack.config.js file to the project with the following code:

JavaScript
"use strict";
 
var webpack = require("webpack");
 
module.exports = {
    "entry": {main: "./wwwroot/main.ts"},
    "output": {        
        filename: "/wwwroot/dist/bundle.js",
        publicPath:"/wwwroot/dist"
    },
    "resolve":{
        extensions:['*','.ts','.webpack','.web.js','.js']
    },
 
    "devtool":'source-map',
 
    "module": {
        loaders: [
            { test: /\.ts$/,
              loader:'awesome-typescript-loader'
            }
        ]
    },
    "plugins": [
        //configure plug in
    ]
}

Finally, the project structure should look like this:

The next step is add folder app to the wwwroot with files, app.component.ts, app.component.html and app.module.ts.

JavaScript
//app.component.ts

import { Component } from '@angular/core';
 
@Component({
    selector: 'my-app',
    templateUrl:'./app/app.component.html'
})
export class AppComponent {
    title = "Welcome to Angular";
} 

//app.component.html

<h1>{{title}}</h1>

//app.module.ts
 
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component'
 
@NgModule({
    imports: [BrowserModule],
    declarations: [AppComponent],
    bootstrap: [AppComponent]
})
export class AppModule{
}

Then, add polyfills.ts file to the wwwroot folder outside the app folder with code as:

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

Then, add main.ts file to the wwwroot folder same like pollyfills.ts:

JavaScript
import './polyfills';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';
 
platformBrowserDynamic().bootstrapModule(AppModule);

Finally, add the index.html page to the wwwroot folder like the above files:

HTML
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
   <script type="text/javascript" src="dist/bundle.js"></script>
</head>
<body>
    <my-app>Loading....</my-app>
</body>
</html>

Build the project using Ctrl+Shift+B and see to it that no errors are found during compilation, then browse through the directory containing the package.json file from node js the command prompt and run "webpack" command so that it should generate the bundle.js file in the wwwroot/dist/bundle.js. Now execute the project using Ctrl+F5 which will build and run the project without debugging. You can see "Welcome to Angular" in your browser.

Points of Interest

We can now start learning how to deploy and run this project in various environments like UAT and PROD by just deploying the bundle.js file.

I am open for any suggestions. Thanks for reading this post.

History

  • 23rd July, 2017: Initial version

License

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


Written By
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Member 1332701924-Jul-17 21:15
Member 1332701924-Jul-17 21:15 
QuestionEverything here is rather old... Pin
Dewey24-Jul-17 7:08
Dewey24-Jul-17 7:08 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.