如何使用angular 4 開發Server端rendering 程序, Friendly SEO.

我最近在一個新的項目中想使用angular 4來寫前端,可是如今不是全部的搜索引擎都支持動態文本的,因此最好的辦法就是在服務端輸出完整的html代碼,目前angular能夠支持nodejs, .net core的服務端渲染了,我目前對.net core 服務端渲染不是很熟悉,下面的例子是Nodejs 使用express部署 angular4 進行服務端渲染。html

建立angular項目,使用@angular/cli 組件來建立參考:http://www.cnblogs.com/sgciviolence/p/6441497.html前端

> ng new ang4-seo --routing
> cd ang4-seo

服務端渲染必須添加platform-server引用,和animations引用node

> npm install --save @angular/platform-server @angular/animations

而後修改/src/app/app.module.ts文件express

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule.withServerTransition({appId: 'ang4-seo-pre'}),
    FormsModule,
    HttpModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

  

建立/src/app/app.server.module.ts 文件

 

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 { }

建立Express Server, /src/server.ts

import 'reflect-metadata';
import 'zone.js/dist/zone-node';
import { platformServer, renderModuleFactory } from '@angular/platform-server'
import { enableProdMode } from '@angular/core'
import { AppServerModuleNgFactory } from '../dist/ngfactory/src/app/app.server.module.ngfactory'
import * as express from 'express';
import { readFileSync } from 'fs';
import { join } from 'path';

const PORT = 4000;

enableProdMode();

const app = express();

let template = readFileSync(join(__dirname, '..', 'dist', 'index.html')).toString();

app.engine('html', (_, options, callback) => {
  const opts = { document: template, url: options.req.url };

  renderModuleFactory(AppServerModuleNgFactory, opts)
    .then(html => callback(null, html));
});

app.set('view engine', 'html');
app.set('views', 'src')

app.get('*.*', express.static(join(__dirname, '..', 'dist')));

app.get('*', (req, res) => {
  res.render('index', { req });
});

app.listen(PORT, () => {
  console.log(`listening on http://localhost:${PORT}!`);
});

  

TypeScript Config 修改

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/app",
    "module": "es2015",
    "baseUrl": "",
    "types": []
  },
  "exclude": [
    "server.ts",    // 這裏
    "test.ts",
    "**/*.spec.ts"
  ]
}

  而後, 打開 /tsconfig.json 添加 angularCompilerOptions:npm

{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "baseUrl": "src",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2016",
      "dom"
    ]
  },
  "angularCompilerOptions": {                             // 這裏
      "genDir": "./dist/ngfactory",
      "entryModule": "./src/app/app.module#AppModule"
  }  
}

 

修改package.json

{
  //
  // Other properties removed for brevity
  //

  "scripts": {
    "prestart": "ng build --prod && ngc",
    "start": "ts-node src/server.ts"
  },

  //
  // Other properties removed for brevity
  //

}
ng build --prod && ngc 會先編譯項目。

服務端運行:



> npm run start

開發調試,運行

> ng serve json

 

文章參考來自:bootstrap

https://coursetro.com/posts/code/68/Make-your-Angular-App-SEO-Friendly-(Angular-4-+-Universal)app

相關文章
相關標籤/搜索