aspnetcore-angular-universal icon indicating copy to clipboard operation
aspnetcore-angular-universal copied to clipboard

[Feature] Transition to Angular-CLI based template

Open MarkPieszak opened this issue 7 years ago • 30 comments

Now that we have transitioned to 5.0, the next step is to move things to the Angular-CLI based template, which should be (almost) a drop-in replacement for most of the apps built with this template.

The best part will be webpack configuration and everything will be handled by the CLI, and we'll have MUCH better (smaller) bundles etc.

MarkPieszak avatar Jan 23 '18 20:01 MarkPieszak

Quick question, The ng-cli will output webpack config, will it not? It's nice to have for extra customisation

mcgri avatar Jan 24 '18 10:01 mcgri

It won't unfortunately, but there are ways to hack/insert rules you can do - so that you don't have to leave the CLI itself :) @mcgri

For example here, I have a writeup on adding pug rules to a CLI that hasn't been ejected. https://medium.com/@MarkPieszak/using-pug-or-jade-templates-with-the-angular-cli-9e37334db5bc

It might be quite hacky, but it gets the job done 😄

I'll try to add a few more upgrades to this setup before the transition, I'm sure I'll just leave this one in a different branch - incase someone does want complete control over Webpack.

MarkPieszak avatar Jan 24 '18 14:01 MarkPieszak

thank you :) I will definitely play with it

mcgri avatar Jan 24 '18 14:01 mcgri

Will the ng-cli template based, output from .cshtml as it is now? or .html as the node version?

Because one of the main reasons we are currently using this template is to do some conditions in the mark up for environments etc... which im not 100% sure how well/easy to handle with just SSR code (perhaps because i havent actually tried much yet)

stephenlautier avatar Feb 05 '18 22:02 stephenlautier

As an Angular template, it should be based on index.html.

odahcam avatar Feb 19 '18 20:02 odahcam

@MarkPieszak do we have any roadmap/milestone/project for this feature?

odahcam avatar Feb 19 '18 20:02 odahcam

I'm waiting on the team to finish up the dependency bundling issue here: https://github.com/angular/angular-cli/issues/8616

I spoke with them just last week that it's very important for the ASP.NET integration so hopefully it'll get in there soon!

It will help production bundle size and overall complexity (since most users won't need to touch the webpack configs) :)

MarkPieszak avatar Feb 20 '18 19:02 MarkPieszak

I've made a node build of my app and it was ridiculous smaller and faster than my asp.net Core one. :(

I hope that this came out soon, so we can finally have service workers on our applications trought @angular/service-worker, this feature refuses to work properly when outside of a @angular/cli build. That's sad.

I wish I could help over there, but there's onyl waiting for now (and seeking for things where I can help). 😞

odahcam avatar Feb 21 '18 00:02 odahcam

Yeah at the moment it's definitely more performant to just have the standalone Node server doing Angular Universal the normal way (outside of ASP.NET, and just use .NET for your Rest API endpoints/etc).

I'll post as soon as I have some updates!

SO so sorry for the wait guys 😢

MarkPieszak avatar Feb 22 '18 23:02 MarkPieszak

Hey @MarkPieszak, seems like the team has solved the https://github.com/angular/angular-cli/issues/8616#issuecomment-373483999 issue. So is there any news about this? 😀

odahcam avatar Mar 21 '18 12:03 odahcam

Bundle went from 200mb~ to 4mb! 27min to 8min production build! 💯

I just get these warnings, but everything still works!

WARNING in ./node_modules/@angular/core/bundles/core.umd.js
6563:23-44 Critical dependency: the request of a dependency is an expression
    at ImportLazyContextDependency.getWarnings (C:\node_modules\webpack\lib\dependencies\ContextDependency.js:39:18)
    at Compilation.reportDependencyErrorsAndWarnings (C:\node_modules\webpack\lib\Compilation.js:703:24)
    at Compilation.finish (C:\node_modules\webpack\lib\Compilation.js:561:9)
    at applyPluginsParallel.err (C:\node_modules\webpack\lib\Compiler.js:502:17)
    at C:\node_modules\tapable\lib\Tapable.js:289:11
    at _addModuleChain (C:\node_modules\webpack\lib\Compilation.js:507:11)
    at processModuleDependencies.err (C:\node_modules\webpack\lib\Compilation.js:477:14)
    at process._tickCallback (internal/process/next_tick.js:150:11)
 @ ./node_modules/@angular/core/bundles/core.umd.js
 @ ./ClientApp/main.server.ts
 @ multi ./ClientApp/main.server.ts

WARNING in ./node_modules/@angular/core/bundles/core.umd.js
6583:23-110 Critical dependency: the request of a dependency is an expression
    at ImportLazyContextDependency.getWarnings (C:\node_modules\webpack\lib\dependencies\ContextDependency.js:39:18)
    at Compilation.reportDependencyErrorsAndWarnings (C:\node_modules\webpack\lib\Compilation.js:703:24)
    at Compilation.finish (C:\node_modules\webpack\lib\Compilation.js:561:9)
    at applyPluginsParallel.err (C:\node_modules\webpack\lib\Compiler.js:502:17)
    at C:\node_modules\tapable\lib\Tapable.js:289:11
    at _addModuleChain (C:\node_modules\webpack\lib\Compilation.js:507:11)
    at processModuleDependencies.err (C:\node_modules\webpack\lib\Compilation.js:477:14)
    at process._tickCallback (internal/process/next_tick.js:150:11)
 @ ./node_modules/@angular/core/bundles/core.umd.js
 @ ./ClientApp/main.server.ts
 @ multi ./ClientApp/main.server.ts

chrisvfabio avatar Mar 22 '18 03:03 chrisvfabio

@MarkPieszak Is this in the works or are we waiting for Angular 6 & CLI v6 to hit release?

aaronwJordan avatar Mar 27 '18 16:03 aaronwJordan

@MarkPieszak can you please check with Angular CLI team about https://github.com/angular/angular-cli/issues/8616 , the issue still exists.

naveedahmed1 avatar Apr 08 '18 19:04 naveedahmed1

If this is still a thing, I've managed to put together a working version of an Angular + ASP.NET Core app with server-side rendering while also using the Angular CLI. I know there is interest in having the bug mentioned above addressed, but I've gotten this type of project to cooperate with Angular CLI just fine based off of the updated ASP.NET Core + Angular template.

If you'd like me to, I could give this setup a go with this repo and see if I can get it to work with this kit and submit a PR. Just let me know if you'd like this and I can get on it ASAP.

Xoadra avatar May 03 '18 16:05 Xoadra

@Xoadra Please do!

aaronwJordan avatar May 03 '18 19:05 aaronwJordan

Spoke with Hans from the CLI team and we should be fine with https://github.com/angular/angular-cli/issues/8616 since we can simply just not use the buildOptimizer as it wouldn't benefit us during SSR renders anyway.

It'd be great to switch things over to the CLI template so that we can get everyone on the same page with Steves CLI templates 👍

MarkPieszak avatar May 05 '18 18:05 MarkPieszak

Yup he updated the issue yesterday and I think there is some progress as well.

naveedahmed1 avatar May 05 '18 18:05 naveedahmed1

Great :) Also I think in terms of #609, we might have to take on aspnet-prerendering ourselves since it might not be updated by the aspnet team anymore.

MarkPieszak avatar May 05 '18 18:05 MarkPieszak

Do I misunderstand anything? It seems like dotnet core + angular cli + ssr is official support by MS here

https://docs.microsoft.com/en-us/aspnet/core/spa/angular?view=aspnetcore-2.1&tabs=visual-studio

maxisam avatar Jun 18 '18 16:06 maxisam

I think the goal was to try and merge both efforts, but it might be better to give people options - and have them seperate. I haven't spoken with Steve Sanderson in a bit, maybe I can touch base with him and talk about the future of that project and what else we can do!

MarkPieszak avatar Jun 22 '18 15:06 MarkPieszak

@MarkPieszak in my experience I found the new Angular CLI based template very good. The only thing what I think was missing is the ability to add Http Status code (for example 404 for not found pages), but the recent version has this ability as well. Though I am not sure about the best way to use it. I would appreciated, if you could review this and suggest improvements.

https://stackoverflow.com/a/50937983/2755616

naveedahmed1 avatar Jun 22 '18 15:06 naveedahmed1

We are using CLI to build browser and server bundles but we still using @MarkPieszak example to integrate Angular and .Net Core (SpaServices). Our journey was the following:

  • 1 year ago when we started our project we used CLI for browser bundles and webpack for server bundles. We had in fact 2 build processes but we used CLI for browser bundles from scratch
  • Right now (after upgrading to Angular 6) we are migrating server bundles build process to CLI and it works fine! We follow official Angular docs to run Universal + some custom code to specify LAZY_MODULE_MAP from main server bundle + bundleDependencies=all + optimization=false. All Angular code is still the same like it is in Mark's repository

So, I confirm you can build project with CLI only and run it under .Net Core with the same .Net Core integration like is presented in the current repository. You don't need completely move to new MS template to run Angular Universal under .Net Core.

skhalipski avatar Sep 06 '18 11:09 skhalipski

@skhalipski have you tried the default template ASP.NET Core SPA template for Angular CLI projects? I think its pretty stable now.

naveedahmed1 avatar Sep 06 '18 17:09 naveedahmed1

@naveedahmed1 I hope we will migrate to new template later. With quite big project in PROD it is not so easy to do because of the following reasons;

  • Pre-rendering cache
  • Security
  • Cookies managements from/to Angular/.NET
  • Logs extracting from Node to .NET and so on

All these custom features are working in old template but they are not available/or it is unclear how they are working in new template. For this reason we are still in the current template of Angular/.NET integration but CLI instead of webpack.

skhalipski avatar Sep 07 '18 08:09 skhalipski

@skhalipski

By Pre-rendering if you are referring to transfer state so that http requests aren't executed twice i.e. once server and then again on client. Then you may try creating an Http Interceptor like this:

import { isPlatformServer } from '@angular/common';
import { HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse } from '@angular/common/http';
import { Inject, Injectable, PLATFORM_ID } from '@angular/core';
import { makeStateKey, TransferState } from '@angular/platform-browser';
import { Observable, of } from 'rxjs';
import { catchError, tap } from 'rxjs/operators';

const CACHE_KEY = makeStateKey('httpCacheKey');

@Injectable()
export class MyHttpInterceptor implements HttpInterceptor {

  private isServer = isPlatformServer(this.platformId);

  constructor(@Inject(PLATFORM_ID) private platformId, private transferState: TransferState) { }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    //for GET requests check cache and if found, return cached response
    if (req.method == 'GET') {
      let cachedResponse: HttpResponse<any> = this.getCachedResponse();
      if (cachedResponse) {
        return of(cachedResponse);
      }
    }

    return next.handle(req)
      .pipe(
        tap((event: HttpEvent<any>) => {
        if (event instanceof HttpResponse) {
            if (this.isServer && req.method == 'GET') {
              this.transferState.set(CACHE_KEY, event as any);
            }
          }
        }),
        catchError((err) => {
          return this.handleError(err);
        }));
  }

  getCachedResponse(): HttpResponse<any> {
    const cachedResponse = this.transferState.get(CACHE_KEY, null as any);
    if (cachedResponse) {
      this.transferState.remove(CACHE_KEY);
      let modifiedResponse = new HttpResponse<any>({ headers: cachedResponse.headers, body: cachedResponse.body, status: cachedResponse.status, statusText: cachedResponse.statusText, url: cachedResponse.url });
      return modifiedResponse;
    }
    return null;
  }

  private handleError(err: HttpErrorResponse): Observable<any> {
    //do any error handling
    return of(err);
  }
}

For security this may help https://angular.io/guide/security

Cookies management should work the way you are handling it in this template.

Logs extracting from Node to .NET I'm not sure what do you mean by this.

naveedahmed1 avatar Sep 07 '18 21:09 naveedahmed1

Hey @MarkPieszak, I've managed to create an Angular CLI project served with aspnet, build server and client bundles with angular cli, but when trying to add hot module replacement comes the trouble. Dotnet's UseWebpackDevMiddleware seems to be needing to see a webpack.config file. There is none since I use angular cli to build project, and now they depreciated ng eject and the file on node_modules.

Any suggestions? I'm thinking of using Steve Sanderson's dotnet template https://docs.microsoft.com/en-us/aspnet/core/client-side/spa/angular?view=aspnetcore-2.1&tabs=visual-studio

guidodizi avatar Nov 01 '18 14:11 guidodizi

@guidodizi Yea the JavaScriptServices template would work great. It does have some issues with SSR and a few deployment bundle issues - but it's definitely solid! I'll have to try and push those issues forward and try to get them resolved on the AngularCLI-end so that at least that template can do all of that properly!

It might be worth keeping these 2 separate, for those who want complete control over their build (webpack) process / etc. The nice thing is that most of the time the webpack configs included here don't have to be touched/tweaked much. I am way overdue to give this whole repo some much needed love and upgrade things & fix a few things here and there though.

I've been meaning to catch up with Steve but been so busy, I'll try to have a call with him to hear what he thinks about everything!

MarkPieszak avatar Nov 04 '18 03:11 MarkPieszak

+1

curlyfro avatar Nov 04 '18 15:11 curlyfro

Any updates on timelines for this? The currently ejected-webpack implementation is not optimal for a sample project referenced by the official angular-universal docs.

andlewis avatar Mar 14 '19 15:03 andlewis

Is there any update regarding this?

AsifulNobel avatar Jun 28 '19 15:06 AsifulNobel