要实现Angular的服务器端渲染(Server Side Rendering, SSR)和Progressive Web App(PWA),可以按以下步骤进行操作:
ng new my-app
cd my-app
ng add @nguniversal/express-engine
ng generate universal --client-project my-app
const express = require('express');
const { join } = require('path');
const { ngExpressEngine } = require('@nguniversal/express-engine');
const app = express();
const PORT = process.env.PORT || 4000;
const DIST_FOLDER = join(process.cwd(), 'dist/my-app');
app.engine('html', ngExpressEngine({
bootstrap: AppServerModule,
}));
app.set('view engine', 'html');
app.set('views', DIST_FOLDER);
app.get('*.*', express.static(DIST_FOLDER));
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 my-app:server",
"serve:ssr": "node server.js"
}
npm run build:ssr
npm run serve:ssr
现在,你的Angular应用程序将以服务器端渲染的方式运行。
要将Angular应用程序转换为Progressive Web App(PWA),可以按照以下步骤进行操作:
ng add @angular/pwa
"projects": {
"my-app": {
"architect": {
"build": {
"configurations": {
"production": {
"serviceWorker": true
}
}
}
}
}
}
ng build --prod
http-server -p 8080 -c-1 dist/my-app
现在,你的Angular应用程序将作为Progressive Web App(PWA)运行,并具有离线访问和其他PWA功能。