Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Is there any guide how to enable SSR for Angular6 template? #5423

Closed
michael-vasyliv opened this issue Jun 28, 2018 · 21 comments
Closed

Is there any guide how to enable SSR for Angular6 template? #5423

michael-vasyliv opened this issue Jun 28, 2018 · 21 comments
Labels
area-mvc Includes: MVC, Actions and Controllers, Localization, CORS, most templates question
Milestone

Comments

@michael-vasyliv
Copy link

Is there any guide how to enable SSR for Angular6 template?

@esoderquist
Copy link

esoderquist commented Jul 3, 2018

I just went through this last week upgrading an Angular 6 project with SSR. Documentation is still evolving (see dotnet/AspNetCore.Docs#7310) - aside from the changes in #581, you'll need the following pieces in place:

angular.json - add a new project that builds via @angular-devkit/build-angular:server. Note that below, I'm specifically not optimizing my server bundle and bundling all dependencies to avoid having to ship my node_modules folder to production pending optimization fixes upstream in angular (angular/angular-cli#8616).

"ssr": {
      "root": "",
      "sourceRoot": "src",
      "projectType": "application",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:server",
          "options": {
            "outputPath": "dist-server",
            "main": "src/main.server.ts",
            "tsConfig": "src/tsconfig.server.json"
          },
          "configurations": {
            "production": {
              "optimization": false,
              "outputHashing": "media",
              "sourceMap": false,
              "namedChunks": false,
              "extractLicenses": true,
              "vendorChunk": false,
              "bundleDependencies": "all"
            }
          }
        }
      }
    }

package.json - update build scripts to reflect the following

    "start": "ng serve",
    "build": "ng build",
    "build:ssr": "ng build --configuration=production --project=ssr",

Also in package.json, make sure you have a devDependencies for @angular-devkit/build-angular. Note that as of right now, you'll need version 0.7.0-rc.0 to enable --watch functionality to rebuild your server bundle during development. See angular/angular-cli#11415. Production SSR should work with @angular-devkit/build-angular 0.6.8, but you won't get --watch functionality during development.

Startup.cs - one minor deviation from the switch to @angular-devkit/build-angular. The file produced by @angular-devkit/build-angular is different, so adjust main.bundle.js to main.js

app.UseSpa(spa =>
      {
        // To learn more about options for serving an Angular SPA from ASP.NET Core,
        // see https://go.microsoft.com/fwlink/?linkid=864501

        spa.Options.SourcePath = "ClientApp";

        spa.UseSpaPrerendering(options =>
        {
          options.BootModulePath = $"{spa.Options.SourcePath}/dist-server/main.js";
          options.BootModuleBuilder = env.IsDevelopment()
              ? new AngularCliBuilder(npmScript: "build:ssr")
              : null;
          options.ExcludeUrls = new[] { "/sockjs-node" };
        });

        if (env.IsDevelopment())
        {
          spa.UseAngularCliServer(npmScript: "start");
        }
      });

@latchezar-kostov-ascendlearning-com

@esoderquist I seem to get the following error:

The module at ClientApp/dist-server/main.js does not export a default function, and you have not specified which export to invoke.

@michael-vasyliv
Copy link
Author

michael-vasyliv commented Aug 7, 2018

@esoderquist Thanks for your answer. I've followed your instructions and got an error

> ng build --configuration=production --project=ssr "--watch"



Microsoft.AspNetCore.SpaServices:Information: Date: 2018-08-07T10:51:52.327Z
Hash: a9a0aceff7cf4545e284
Time: 8736ms
chunk {main} main.js, main.js.map (main) 27.7 kB [initial] [rendered]
chunk {polyfills} polyfills.js, polyfills.js.map (polyfills) 227 kB [initial] [rendered]
chunk {runtime} runtime.js, runtime.js.map (runtime) 5.22 kB [entry] [rendered]
chunk {styles} styles.css, styles.css.map (styles) 130 kB [initial] [rendered]
chunk {vendor} vendor.js, vendor.js.map (vendor) 3.83 MB [initial] [rendered]
i я╜вwdmя╜г: Compiled successfully.

The thread 0x3148 has exited with code 0 (0x0).
The thread 0x28c4 has exited with code 0 (0x0).
The thread 0xea4 has exited with code 0 (0x0).
The thread 0x3458 has exited with code 0 (0x0).
The thread 0x1ea8 has exited with code 0 (0x0).
The thread 0x5ec has exited with code 0 (0x0).
'dotnet.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\2.1.2\System.Diagnostics.StackTrace.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'dotnet.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\2.1.2\System.Reflection.Metadata.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware:Error: An unhandled exception has occurred while executing the request.

System.TimeoutException: The prerendering build process did not complete within the timeout period of 50 seconds. Check the log output for error information.
   at Microsoft.AspNetCore.SpaServices.Extensions.Util.TaskTimeoutExtensions.WithTimeout(Task task, TimeSpan timeoutDelay, String message)
   at Microsoft.AspNetCore.Builder.SpaPrerenderingExtensions.<>c__DisplayClass0_0.<<UseSpaPrerendering>b__1>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)
   at Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 50188.2272ms 500 text/html; charset=utf-8

here is a link with changes https://github.com/vasyliv/angular6/tree/angular-server

@esoderquist
Copy link

esoderquist commented Aug 7, 2018

@vasyliv I suspect you're hitting aspnet/JavaScriptServices#1619, which leads to development-time SSR failing to detect that @angular-devkit/build-angular has finished building. PR aspnet/JavaScriptServices#1620 should address the root issue.

@michael-vasyliv
Copy link
Author

michael-vasyliv commented Aug 8, 2018

@esoderquist I've added the script to avoid the flag --watch and I've got this error

System.AggregateException: One or more errors occurred. (The NPM script 'build:ssr' exited without indicating success.
Output was: 

> angular6@0.0.0 build:ssr E:\TEST\Angular-CSharp\ClientApp
> npm run build:ssr_trick "--watch"



> angular6@0.0.0 build:ssr_trick E:\TEST\Angular-CSharp\ClientApp
> ng build --configuration=production --project=ssr




Error output was: ) ---> System.InvalidOperationException: The NPM script 'build:ssr' exited without indicating success.
Output was: 

> angular6@0.0.0 build:ssr E:\TEST\Angular-CSharp\ClientApp
> npm run build:ssr_trick "--watch"



> angular6@0.0.0 build:ssr_trick E:\TEST\Angular-CSharp\ClientApp
> ng build --configuration=production --project=ssr




Error output was:  ---> System.IO.EndOfStreamException: Attempted to read past the end of the stream.
   at Microsoft.AspNetCore.SpaServices.AngularCli.AngularCliBuilder.Build(ISpaBuilder spaBuilder)
   --- End of inner exception stack trace ---
   at Microsoft.AspNetCore.SpaServices.AngularCli.AngularCliBuilder.Build(ISpaBuilder spaBuilder)
   --- End of inner exception stack trace ---
   at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
   at System.Threading.Tasks.Task.Wait()
   at Microsoft.AspNetCore.SpaServices.Extensions.Util.TaskTimeoutExtensions.WithTimeout(Task task, TimeSpan timeoutDelay, String message)
   at Microsoft.AspNetCore.Builder.SpaPrerenderingExtensions.<>c__DisplayClass0_0.<<UseSpaPrerendering>b__1>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)
   at Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
---> (Inner Exception #0) System.InvalidOperationException: The NPM script 'build:ssr' exited without indicating success.

after click F5 the project works fine.

@SteveSandersonMS Could you clarify the version of AngularCliMiddlewareExtensions with the bug-fix (aspnet/JavaScriptServices#1620) for the error above? Where original issue is aspnet/JavaScriptServices#1619

@c3mohamn
Copy link

c3mohamn commented Aug 10, 2018

@vasyliv I started getting that error when I updated to dotnet core 2.1.1 from 2.1.0. Worked after refresh as well.

Did not get the error on 2.1.0 and seems to work on 2.1.2 as well.

@michael-vasyliv
Copy link
Author

@c3mohamn yes, you are right but do all time the refresh of the page is a bad idea, I can't say that it works fine.

@michael-vasyliv
Copy link
Author

up

@bastienlemaitre
Copy link

Up

@michael-vasyliv
Copy link
Author

up

1 similar comment
@papiliond
Copy link

up

@BeejeeDS
Copy link

BeejeeDS commented Sep 30, 2018

The task to update the documentation has been on just moved to another sprint for the 4th time.
How is that even possible, MS just update the damn file already.

@mbrewerton
Copy link

I've followed the documentation from the .Net Core docs along with what @esoderquist has suggested but I'm still getting The prerendering build process did not complete within the timeout period of 50 seconds. Check the log output for error information. every. time.

This is incredibly frustrating because the app that I'm building will need to utilise SSR for SEO and potentially performance purposes. I guess I should just plough on without SSR and wait for the official ASP.Net document update (if that ever happens...)

@adamcweitzman
Copy link

adamcweitzman commented Oct 10, 2018

getting:

Unexpected end of file.
Error: Unexpected end of file.

11154

looks like its hashtags and CSR for me :(

@HesamKashefi
Copy link

Is there anyone who can create a repo with a sample of asp.net core + angular 6 and SSR enabled , I'm stuck in this since last week!

@ghost
Copy link

ghost commented Oct 16, 2018

There is the one of @vasyliv https://github.com/vasyliv/angular6/tree/angular-server
I was able to make it run it render ssr only the home page i use Postman and got all the html, i cannot get the two other page to render all the content
here is my vscode launch.json
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": ".NET Core Launch (full)",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build",
"program": "${workspaceFolder}/bin/Debug/netcoreapp2.1/Angular-CSharp.dll",
"args": [],
"cwd": "${workspaceFolder}",
"stopAtEntry": false,
"internalConsoleOptions": "openOnSessionStart",
"launchBrowser": {
"enabled": false
},
"env": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"sourceFileMap": {
"/Views": "${workspaceFolder}/Views"
}
},
{
"type": "chrome",
"request": "launch",
"name": "Chrome",
"url": "http://localhost:5000",
"webRoot": "${workspaceFolder}/wwwroot"
}
],
"compounds": [
{
"name": "Full stack",
"configurations": [".NET Core Launch (full)", "Chrome"]
}
]
}

I try a bunch let me know if you have any luck.

@michael-vasyliv
Copy link
Author

@jfborie yes, you are right, i have this issue in angular 5 and angular 6 but it is not critical for me, due to the reason that it's the issue with fiddler and postman, if i load by browser it will work fine, to sum up in prod on your site it will work fine too.

@HesamKashefi
Copy link

@jfborie thanks, I used that sample and it helped but my app was not still working, after 10 days! I finally found out that the problem was reading a config file in my AppModule from assets folder and in the server It was not available so I had no results!

@jasonhulbert
Copy link

@HesamKashefi What config file are you referring to? The environment.ts config? I'm getting the same The prerendering build process did not complete within the timeout period of 50 seconds error.

@HesamKashefi
Copy link

@jasonhulbert I have a path to a configuration file saved in my environment.ts file which is a just a relative path to a folder inside assets. In my app.module I use a Provider with injection token APP_INITIALIZER that has a factory method that I use to load my config file base on the environment (Dev, Prod) and use it in my app.
I use HttpClient of angular to load that configuration.


import { environment } from '../environments/environment';

export function ConfigLoader(configService: ConfigService) {
  return () => configService.load(environment.configFile);
}

@NgModule({
…
  providers: [
    ConfigService,
    {
      provide: APP_INITIALIZER,
      useFactory: ConfigLoader,
      deps: [ConfigService],
      multi: true
    },
…
]
})
export class AppModule { }

and inside my configService:

load(url: string) {
    return new Promise((resolve, reject) => {
        this._http.get<Config>(url).subscribe(
          config => {
            this.config = config;
            resolve(config);
          },
          e => {
            reject(e);
          }
        );
      
    });
  }

this was my problem!
I fixed it by modifying load method of my configService to get config from server code when running in server side.

I still get that timeout error on first load in debug but it just needs a F5 to refresh the page...

@aspnet-hello aspnet-hello transferred this issue from aspnet/Templating Dec 17, 2018
@aspnet-hello aspnet-hello added this to the Discussions milestone Dec 17, 2018
@aspnet-hello aspnet-hello added area-mvc Includes: MVC, Actions and Controllers, Localization, CORS, most templates question labels Dec 17, 2018
@aspnet-hello
Copy link

We periodically close 'discussion' issues that have not been updated in a long period of time.

We apologize if this causes any inconvenience. We ask that if you are still encountering an issue, please log a new issue with updated information and we will investigate.

@dotnet dotnet locked and limited conversation to collaborators Mar 11, 2019
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
area-mvc Includes: MVC, Actions and Controllers, Localization, CORS, most templates question
Projects
None yet
Development

No branches or pull requests