Setup Server Side Rendering Angular 4+ Application with Loopback/Strongloop

点点圈 提交于 2019-12-24 03:23:46

问题


I have a Loopback-Server as backend for my angular application and it works great. To improve my SEO on my application I want to render the application on the server (ssr).

I have my angular application inside the client folder of the loopback server application

the /client/dist folder is where the generated angular files are stored. the /client/frontend folder is where the source application is in.

my question is how to setup the tsconfig.json file. my angularCompilerOptions look like this:

    "angularCompilerOptions": {
        "genDir": "../dist",
        "entryModule": "./src/app/app.module#AppModule"
    }

on top of that I generated a app.server.module.ts file inside the src/app/ folder to export the AppServerModule.

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

and a server.ts file inside the src/ folder:

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}!`);
});

my question is:

  • do I really need the express server inside the server.ts file ?
  • can I tell loopback to serve the files already rendered ?
  • how can I achieve SSR with Loopback ?

just for the completeness: I am using angular 5.2.0 and loopback 3.x

thanks for all helpful answers


回答1:


With Angular you must use Universal if you want to make the app SEO friendly.

If you want another option then GoogleChrome recently launched Rendertron. It serve the rendered pages to Bots.



来源:https://stackoverflow.com/questions/49985165/setup-server-side-rendering-angular-4-application-with-loopback-strongloop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!