As usual, we will start the project with the Angular CLI. Check out our Free Angular Course if you're new to the CLI.
> ng new ang4-seo --routing
> cd ang4-seo
The --routing flag will generate a quick routes file and add it to our app module.
Once we're in the new project folder, we'll use npm to install the platform-server, which is needed for server side rendering and generating HTML pages. We also must install the animations package (new to Angular v4), otherwise your app will result in an error:
> npm install --save @angular/platform-server @angular/animations
Next, we'll head into /src/app/app.module.ts and make a slight adjustment:
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule.withServerTransition({appId: 'ang4-seo-pre'}),
FormsModule,
HttpModule
],
providers: [],
bootstrap: [AppComponent]
})
The only line that is changed is the BrowserModule. Here, we've added a .withServerTransition which takes in an appId that is shared between the client and the server. .withServerTransition allows Universal to replace the HTML it generated on its own.
Save this file.
Create a Server App Module
Create a new file called /src/app/app.server.module.ts and paste in the following code:
import { NgModule } from '@angular/core';
import { ServerModule } from '@angular/platform-server';
import { AppModule } from './app.module';
import { AppComponent } from './app.component';
@NgModule({
imports: [
ServerModule,
AppModule
],
bootstrap: [AppComponent]
})
export class AppServerModule { }
This is used to bootstrap the app from the server. If you compare it against /src/app/app.module.ts, they're very similar. The main takeaway here is that this module is for the server.
- Войдите или зарегистрируйтесь, чтобы оставлять комментарии