在Angular 8中实现动态路由上的SEO图片和内容,可以通过以下步骤来解决:
npm install @angular/platform-server --save
import 'zone.js/dist/zone-node';
import 'reflect-metadata';
import { enableProdMode } from '@angular/core';
import { renderModuleFactory } from '@angular/platform-server';
import { provideModuleMap } from '@nguniversal/module-map-ngfactory-loader';
import { readFileSync } from 'fs';
import { join } from 'path';
import * as express from 'express';
enableProdMode();
const app = express();
const distFolder = join(process.cwd(), 'dist/browser');
const indexHtml = readFileSync(join(distFolder, 'index.html'), 'utf8');
const { AppServerModuleNgFactory, LAZY_MODULE_MAP } = require('./dist/server/main');
app.engine('html', (_, options, callback) => {
const opts = { document: indexHtml, url: options.req.url };
renderModuleFactory(AppServerModuleNgFactory, {
document: indexHtml,
url: options.req.url,
extraProviders: [
provideModuleMap(LAZY_MODULE_MAP)
]
})
.then(html => callback(null, html));
});
app.set('view engine', 'html');
app.set('views', distFolder);
app.get('*.*', express.static(distFolder, {
maxAge: '1y'
}));
app.get('*', (req, res) => {
res.render('index', { req });
});
app.listen(4000, () => {
console.log('Angular Universal Node Express server listening on http://localhost:4000');
});
"architect": {
"build": {
"options": {
...
"outputPath": "dist/browser",
"index": "src/index.html",
...
},
...
},
"server": {
"builder": "@angular-devkit/build-angular:server",
"options": {
"outputPath": "dist/server",
"main": "src/main.server.ts",
"tsConfig": "src/tsconfig.server.json"
},
...
}
}
export { AppServerModule } from './app/app.server.module';
"compilerOptions": {
...
"module": "commonjs",
"types": ["node"],
...
}
import { NgModule, APP_INITIALIZER } from '@angular/core';
...
import { Meta, Title } from '@angular/platform-browser';
export function initializeApp(meta: Meta, title: Title) {
return () => {
title.setTitle('My App');
meta.addTags([
{ name: 'description', content: 'My App Description' },
{ property: 'og:title', content: 'My App' },
{ property: 'og:description', content: 'My App Description' },
{ property: 'og:image', content: 'https://example.com/my-app-image.jpg' },
{ name: 'twitter:title', content: 'My App' },
{ name: 'twitter:description', content: 'My App Description' },
{ name: 'twitter:image', content: 'https://example.com/my-app-image.jpg' }
]);
};
}
@NgModule({
...
providers: [
...
{
provide: APP_INITIALIZER,
useFactory: initializeApp,
deps: [Meta, Title],
multi: true
}
],
...
})
const { AppServerModuleNgFactory, LAZY_MODULE_MAP } = require('./dist/server/main');
ng build --prod
node server.js
这样就完成了在Angular 8动态路由上实现SEO图片和内容的解
上一篇:Angular 8动态动画