From 这个博客 (网络存档备份)
First npm install --save @angular/platform-server @angular/animations
Edit /src/app/app.module.ts
并将 BrowserModule 导入更改为BrowserModule.withServerTransition({appId: 'your-app-name'}),
创建文件/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 { }
创建文件/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}!`);
});
Edit /src/tsconfig.app.json
并添加server.ts
to the exclude
array
Edit /tsconfig.json
并在之后"compilerOptions"
节点添加以下内容
"angularCompilerOptions": {
"genDir": "./dist/ngfactory",
"entryModule": "./src/app/app.module#AppModule"
}
Edit package.json
并改变"scripts"
部分通过添加"prestart"
并改变"start"
"prestart": "ng build --prod && ngc",
"start": "ts-node src/server.ts"
您现在可以输入npm run start
在你的控制台/终端窗口中,它将构建所有内容并开始在端口 4000 上提供服务。
它不会监视源代码或进行热模块替换等,但是一旦服务器运行,您也可以输入ng serve
(假设您正在使用 @angular/cli npm 包)在另一个窗口中并像平常一样编辑您的单页应用程序并使用npm run start
仅在重建或更改服务器代码时。