Is there any guide how to enable SSR for Angular6 template?
I just went through this last week upgrading an Angular 6 project with SSR. Documentation is still evolving (see https://github.com/aspnet/Docs/issues/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 (https://github.com/angular/angular-cli/issues/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 https://github.com/angular/angular-cli/issues/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");
}
});
@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.
@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
@vasyliv I suspect you're hitting https://github.com/aspnet/JavaScriptServices/issues/1619, which leads to development-time SSR failing to detect that @angular-devkit/build-angular has finished building. PR https://github.com/aspnet/JavaScriptServices/pull/1620 should address the root issue.
@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:
> [email protected] build:ssr E:\TEST\Angular-CSharp\ClientApp
> npm run build:ssr_trick "--watch"
> [email protected] 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:
> [email protected] build:ssr E:\TEST\Angular-CSharp\ClientApp
> npm run build:ssr_trick "--watch"
> [email protected] 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 (https://github.com/aspnet/JavaScriptServices/pull/1620) for the error above? Where original issue is https://github.com/aspnet/JavaScriptServices/issues/1619
@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.
@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.
up
Up
up
up
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.
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...)
getting:
Unexpected end of file.
Error: Unexpected end of file.
looks like its hashtags and CSR for me :(
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!
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.
@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.
@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!
@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.
@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...
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.
Most helpful comment
I just went through this last week upgrading an Angular 6 project with SSR. Documentation is still evolving (see https://github.com/aspnet/Docs/issues/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 (https://github.com/angular/angular-cli/issues/8616).
package.json - update build scripts to reflect the following
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 https://github.com/angular/angular-cli/issues/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