Add Angular 5 CLI project to ASP.Net Core 2.0 project

Frank Chen
6 min readApr 27, 2018

Update: As Angular released new version every once a while, I created Add The latest Angular CLI project(7.x) to ASP.Net Core 2.1 project to mention how to add an Angular Cli project to ASP.NET Core project.

I recently tried the ASP.NET Core SPA template from VS2017 which is based on Angular. I like the way VS2017 finally can use Angular and WebPack for SPA development. However the template was targeting on Angular 4. Although the new ASP.NET Core 2.1 preview also introduced a new template based on Angular 5, I just don’t want to install ASP.NET Core 2.1 Preview because it requires to install VS 2017 15.6 Preview. ASP.NET Core 2.1.0-preview1 now available explained the detail if you want to know more.

As Angular introduced new Angular Cli command, it helped developers a lot to scaffold a SPA application based on the latest Angular. It also provided code generation and compile function which helped to improve the productivity. From the other hands, ASP.NET Core has fast release pace too. In order to leverage those two tools and don’t depend on Visual Studio team to release latest template for latest Angular support, I am thinking about if there is a way to leverage Angular CLI to create a bare bone ASP.NET Core project which can be edited and debug from VS2017. At the same time, the approach can be reusable when there is a new Angular version coming out. I am going to explain what I did to meet this goal.

Currently, The VS2017 supports to create a web SPA project based on Angular 4.x and has slightly changed the layout to use Bootstrap. When the developers are using Angular CLI, it also helps to create a Angular project structure. The following steps will show you how to merge those two things together to have a Angular CLI generate project worked under ASP.NET Core 2.0 project..

  • Create a ASP.Net project by clicking Add new project->Web->ASP.NET Core Web Application. Select the following options at “New ASP.NET Core Web Application” dialog:
  • .NET Core
  • ASP.NET Core 2.0
  • Web Application (Model-View-Controller)
  • Click “Ok”
  • For example, we name the web project as ASPCoreAngular5 which located at c:\projects\ASPCoreAngular5Sln solution folder.
  • After you created your ASP.NET Core project, you need to turn off the default typescript automatic compiler from your VS2017 project file. What you need to do is to unload the project and open project in a XML editor and add the following lines in your project file.
<PropertyGroup><TargetFramework>netcoreapp2.0</TargetFramework><TypeScriptCompileBlocked>true</TypeScriptCompileBlocked><TypeScriptToolsVersion>Latest</TypeScriptToolsVersion></PropertyGroup>
  • Make sure you have latest node.js including NPM.
  • Run command.exe as administrator and go to ASPCoreAngular5 solution folder, for our sample case, it would be “c:\projects\ASPCoreAngular5Sln”.
  • Make sure you have Angular Cli installed. If you don’t, run the following command which will install Angular CLI globally:
npm install -g @angular/cli@latest
  • Enter the following command to create an Angular Cli with same folder as ASP.NET Core solution. The purpose for that is to have package.json and .angular-cli.json are located at the same level as the ASP.NET Core project folder which is one level below the solution folder. I also used — source-dir ClientApp which makes the Angular App source folder is ClientApp.
  • routing: create routing module.
  • skip-git: skip git creation
  • directory: specify the folder as ClientApp. the client side TS code will be located at ClientApp folder which is under ASPCoreAngular5 project folder.
ng new ASPCoreAngular5 —-routing --skip-git --source-dir ClientApp
  • Once the project is created, you can run ng serve to test the application. As ng server is created an in-memory files for browser use. You need to build the angular project if you want to see the actual JS files.
  • When Angular CLI build a project, it will generate all files to the one defined in .angular-cli.json file. Open up .angular-cli.json file and change the output to “../wwwroot/dist”. This will generate built files to wwwroot folder.
  • root: define the root folder, for our case, “ClientApp” will be the root of TypeScripts.
  • outDir: this is output folder. We are going to generate output files to wwwroot/dist folder which will be reference from index.cshtml.
  • styles: the style css you want to include. If you use bootstrap, you need to include bootstrap css to here.
  • scripts: the JavaScript libraries you want to include. We used bootstrap and jQuery, so that we need to bundle them. You can skip them if you want to include their CDN to index.cshtml.
“apps”: [{“root”: “ClientApp”,“outDir”: “./wwwroot/dist”,“assets”: [“assets”,“favicon.ico”],“index”: “index.html”,“main”: “main.ts”,“polyfills”: “polyfills.ts”,“test”: “test.ts”,“tsconfig”: “tsconfig.app.json”,“testTsconfig”: “tsconfig.spec.json”,“prefix”: “app”,“styles”: [“styles.css”,“../node_modules/bootstrap/scss/bootstrap.scss”],“scripts”: [“../node_modules/jquery/dist/jquery.min.js”,“../node_modules/bootstrap/dist/js/bootstrap.bundle.js”],
  • Go back to command line and make sure you are at project folder (for our case, it will be “c:\projects\ASPCoreAngular5Sln\ASPCoreAngular5”). Type the following command to build your angular solutions. The files will be generated under wwwroot/dist folder. All the libraries and css will be bundled to js files.
Ng build
  • Next, we need to change the ASP.NET Core View to add those generated JS to there. Open up your Views/home/index.cshtml and replace to the following code. <app-root> will be the angular entry point.
@{ViewData[“Title”] = “Home Page”;}<app-root></app-root>
  • Open up _layout.cshtml, removed the original Javascript references and replaced the code to the following:
  • <base href=”~/”>: tell how the base url is.
  • Scripts: reference the script files generated by Angular Cli.
<!DOCTYPE html><html><head><meta charset=”utf-8" /><meta name=”viewport” content=”width=device-width, initial-scale=1.0" /><title>@ViewData[“Title”] — ASPCoreAngular5_2</title><base href=”~/” /></head><body>@RenderBody()<script src=”~/dist/inline.bundle.js” asp-append-version=”true”></script><script src=”~/dist/polyfills.bundle.js” asp-append-version=”true”></script><script src=”~/dist/styles.bundle.js” asp-append-version=”true”></script><script src=”~/dist/vendor.bundle.js” asp-append-version=”true”></script><script src=”~/dist/main.bundle.js” asp-append-version=”true”></script>@RenderSection(“Scripts”, required: false)</body></html>
  • Until now, you should be able to run your ASP.NET Core SPA project by press F5. however, if you want to leverage Angular CLI server for debug purpose, you need to tell your ASP.NET Core application to use Angular CLI server to build your files instead of Visual Studio. The benefit for leveraging Angular CLI server is you don’t have to restart your debug project from Visual Studio. Whenever you save your TypeScript code, Angular CLI server will compile that and Visual Studio debugger is able to pick up whatever changes. In order to do that, you need to add Microsoft.AspNetCore.SpaServices.Extensions package which can be installed from nuget package management.
  • Once you have extension installed, open up startup.cs and add the following highlight part in configure() method to support Angular CLI Server and SPA URL routing:
  • SourcePath: we generated the Angular code at “ClientApp” folder and spa.UseAngularCliServer() method will be called only at development mode.
  • MapSpaFallbackRoute: tell the ASP.NET Core to route the SPA routing.
public void Configure(IApplicationBuilder app, IHostingEnvironment env){if (env.IsDevelopment()){app.UseBrowserLink();app.UseDeveloperExceptionPage();}else{app.UseExceptionHandler(“/Home/Error”);}app.UseSpa(spa =>{spa.Options.SourcePath = “ClientApp”;if (env.IsDevelopment()){spa.UseAngularCliServer(npmScript: “start”);}});app.UseStaticFiles();app.UseMvc(routes =>{routes.MapRoute(name: “default”,template: “{controller=Home}/{action=Index}/{id?}”);routes.MapSpaFallbackRoute(name: “spa-fallback”,defaults: new { controller = “Home”, action = “Index” });});}
  • You can press F5 now to start your application in the browser. We are running at development mode, whenever you change your TypeScript code from Visual Studio, the backend Angular Server will recompile the code and refresh your browser.
  • If you want to generate the code whenever you compile the ASP.NET Core project for deployment, you can add NPM tasks into your pre build process under “Task Runner Explorer”. You will have Angular CLI to compile your code when you build your ASP.NET Core project.

Now, you should have a workable ASP.NET Core project with the latest Angular 5 CLI generated codes. You can create some ASP.NET Core Web API and use Angular CLI to generate your components.

--

--