要将Angular 9.0 SSR应用程序部署到服务器上,您需要遵循以下步骤:
ng build --prod
在Angular 9.0中,启用SSR需要使用Angular Universal。确保您已经按照官方文档(https://angular.io/guide/universal)中的说明配置了Angular Universal。
确保在您的应用程序中安装了必要的依赖项。在package.json文件中添加以下依赖项:
"dependencies": {
"@angular/platform-server": "~9.0.0",
"@nguniversal/module-map-ngfactory-loader": "~9.0.0",
"express": "~4.17.1",
"tslib": "^1.10.0"
}
import 'zone.js/dist/zone-node';
import { renderModuleFactory } from '@angular/platform-server';
import { enableProdMode } from '@angular/core';
import * as express from 'express';
import { readFileSync } from 'fs';
import { join } from 'path';
const { AppServerModuleNgFactory, LAZY_MODULE_MAP } = require('./dist/server/main');
const PORT = process.env.PORT || 4000;
const DIST_FOLDER = join(process.cwd(), 'dist');
enableProdMode();
const app = express();
const template = readFileSync(join(DIST_FOLDER, 'browser', 'index.html')).toString();
const { AppServerModule, LAZY_MODULE_MAP } = require('./dist/server/main');
const { renderModule } = require('@angular/platform-server');
app.engine('html', (_, options, callback) => {
renderModule(AppServerModule, {
document: options.req,
url: options.req.url
}).then(html => {
callback(null, html);
});
});
app.set('view engine', 'html');
app.set('views', join(DIST_FOLDER, 'browser'));
app.get('*.*', express.static(join(DIST_FOLDER, 'browser')));
app.get('*', (req, res) => {
res.render('index', { req });
});
app.listen(PORT, () => {
console.log(`Node server listening on http://localhost:${PORT}`);
});
"scripts": {
"build:ssr": "ng build --prod && ng run your-app:server:production",
"serve:ssr": "node dist/server"
}
npm run build:ssr
npm run serve:ssr
这样,您的Angular 9.0 SSR应用程序将会编译并在服务器上运行。您可以在浏览器中访问http://localhost:4000来查看应用程序。