[英]Serving an angular 10 ssr universal app with i18n using firebase cloud functions
我正在處理一個 monorepo 項目,使用由 3 個應用程序組成的 angular 10 和 nx(托管在 firebase 上):網站、應用程序和管理員。 該網站和應用程序使用內置的 @angular/localize 包進行國際化。
現在,我正在網站中實現 angular Universal,但是每次嘗試訪問我的域中的任何 url 時,我的 https 雲函數都會超時。
這是我到目前為止所做的:
import '@angular/localize/init';
import { enableProdMode } from '@angular/core';
import { environment } from './environments/environment';
if (environment.production) {
enableProdMode();
}
export { AppServerModule } from './app/app.server.module';
export { renderModule, renderModuleFactory } from '@angular/platform-server';
import { NgModule } from '@angular/core';
import { ServerModule } from '@angular/platform-server';
import { AppModule } from './app.module';
import { AppComponent } from './app.component';
@NgModule({
imports: [
AppModule,
ServerModule
],
bootstrap: [AppComponent]
})
export class AppServerModule {}
{
"extends": "./tsconfig.app.json",
"compilerOptions": {
"outDir": "../../dist/out-tsc-server",
"module": "commonjs",
"types": [
"node"
]
},
"files": [
"src/main.server.ts",
"server.ts"
],
"angularCompilerOptions": {
"entryModule": "./src/app/app.server.module#AppServerModule"
}
}
import 'zone.js/dist/zone-node';
import { ngExpressEngine } from '@nguniversal/express-engine';
import * as express from 'express';
import { join } from 'path';
import { AppServerModule } from './src/main.server';
import { APP_BASE_HREF } from '@angular/common';
import { LOCALE_ID } from '@angular/core';
// The Express app is exported so that it can be used by serverless Functions.
// I pass a locale argument to fetch the correct i18n app in the browser folder
export function app(locale: string): express.Express {
const server = express();
// get the correct locale client app path for the server
const distFolder = join(process.cwd(), `apps/functions/dist/website/browser/${locale}`);
// Our Universal express-engine (found @ https://github.com/angular/universal/tree/master/modules/express-engine)
server.engine(
'html',
ngExpressEngine({
bootstrap: AppServerModule,
providers: [{provide: LOCALE_ID, useValue: locale}] // define locale_id for the server
})
);
server.set('views', distFolder);
server.set('view engine', 'html');
// For static files
server.get(
'*.*',
express.static(distFolder, {
maxAge: '1y',
})
);
// For route paths
// All regular routes use the Universal engine
server.get('*', (req, res) => {
// this line always shows up in the cloud function logs
console.log(`serving request, with locale ${locale}, base url: ${req.baseUrl}, accept-language: ${req.headers["accept-language"]}`);
res.render('index.html', {
req,
providers: [{ provide: APP_BASE_HREF, useValue: req.baseUrl }]
});
});
return server;
}
// only used for testing in dev mode
function run(): void {
const port = process.env.PORT || 4000;
// Start up the Node server
const appFr = app('fr');
const appEn = app('en');
const server = express();
server.use('/fr', appFr);
server.use('/en', appEn);
server.use('', appEn);
server.listen(port, () => {
console.log(`Node Express server listening on http://localhost:${port}`);
});
}
// Webpack will replace 'require' with '__webpack_require__'
// '__non_webpack_require__' is a proxy to Node 'require'
// The below code is to ensure that the server is run only when not requiring the bundle.
declare const __non_webpack_require__: NodeRequire;
const mainModule = __non_webpack_require__.main;
const moduleFilename = (mainModule && mainModule.filename) || '';
if (moduleFilename === __filename || moduleFilename.includes('iisnode')) {
console.log('running server');
run();
}
export * from './src/main.server';
import * as functions from 'firebase-functions';
const express = require("express");
const getTranslatedServer = (lang) => {
const translatedServer = require(`../../../dist/website/server/${lang}/main`);
return translatedServer.app(lang);
};
const appSsrEn = getTranslatedServer('en');
const appSsrFr = getTranslatedServer('fr');
// dispatch, as a proxy, the translated server app function to their coresponding url
const server = express();
server.use("/", appSsrEn); // use english version as default
server.use("/fr", appSsrFr);
server.use("/en", appSsrEn);
export const globalSsr = functions.https.onRequest(server);
要構建我的 ssr 應用程序,我使用以下 npm 命令: npm run deploy:pp:functions
from my package.json:
...
"build:ppasprod:all-locales:website": "npm run fb:env:pp && ng build website -c=prod-core-optim,prod-budgets,pp-file-replace,all-locales",
"build:ssr:website": "npm run build:ppasprod:all-locales:website && ng run website:server:production",
"predeploy:website:functions": "nx workspace-lint && ng lint functions && node apps/functions/src/app/cp-universal.ts && ng build functions -c=production",
"deploy:pp:functions": "npm run fb:env:pp && npm run build:ssr:website && npm run predeploy:website:functions && firebase deploy --only functions:universal-globalSsr"
...
基本上,它構建 ssr 應用程序,復制apps/functions 中的dist/website文件夾,構建雲函數,然后將其部署到 firebase。
這是配置的 angular.json:
{
"projects": {
"website": {
"i18n": {
"locales": {
"fr": "apps/website/src/locale/messages.fr.xlf",
"en": "apps/website/src/locale/messages.en.xlf"
}
},
"projectType": "application",
"schematics": {
"@nrwl/angular:component": {
"style": "scss"
}
},
"root": "apps/website",
"sourceRoot": "apps/website/src",
"prefix": "",
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"outputPath": "dist/website/browser",
"deleteOutputPath": false,
"index": "apps/website/src/index.html",
"main": "apps/website/src/main.ts",
"polyfills": "apps/website/src/polyfills.ts",
"tsConfig": "apps/website/tsconfig.app.json",
"aot": true,
"assets": [
"apps/website/src/assets",
{
"input": "libs/assets/src/lib",
"glob": "**/*",
"output": "./assets"
}
],
"styles": [
"apps/website/src/styles.scss",
"libs/styles/src/lib/styles.scss"
],
"scripts": [],
"stylePreprocessorOptions": {
"includePaths": ["libs/styles/src/lib/"]
}
},
"configurations": {
"devlocal": {
"budgets": [
{
"type": "anyComponentStyle",
"maximumWarning": "6kb"
}
]
},
"all-locales": {
"localize": ["en", "fr"]
},
"pp-core-optim": {
"optimization": false,
"i18nMissingTranslation": "error",
"sourceMap": true,
"statsJson": true
},
"pp-file-replace": {
"fileReplacements": [
{
"replace": "apps/website/src/environments/environment.ts",
"with": "apps/website/src/environments/environment.pp.ts"
}
]
},
"prod-budgets": {
"budgets": [
{
"type": "initial",
"maximumWarning": "2mb",
"maximumError": "5mb"
},
{
"type": "anyComponentStyle",
"maximumWarning": "6kb",
"maximumError": "10kb"
}
]
},
"prod-core-optim": {
"i18nMissingTranslation": "error",
"optimization": true,
"outputHashing": "all",
"sourceMap": false,
"extractCss": true,
"namedChunks": false,
"extractLicenses": true,
"vendorChunk": false,
"buildOptimizer": true
}
}
},
"extract-i18n": {
"builder": "@angular-devkit/build-angular:extract-i18n",
"options": {
"browserTarget": "website:build"
}
},
"server": {
"builder": "@angular-devkit/build-angular:server",
"options": {
"outputPath": "dist/website/server",
"main": "apps/website/server.ts",
"tsConfig": "apps/website/tsconfig.server.json",
"externalDependencies": ["@firebase/firestore"],
"stylePreprocessorOptions": {
"includePaths": ["libs/styles/src/lib/"]
}
},
"configurations": {
"production": {
"outputHashing": "media",
"fileReplacements": [
{
"replace": "apps/website/src/environments/environment.ts",
"with": "apps/website/src/environments/environment.prod.ts"
}
],
"sourceMap": false,
"optimization": true,
"localize": ["en", "fr"]
}
}
},
"serve-ssr": {
"builder": "@nguniversal/builders:ssr-dev-server",
"options": {
"browserTarget": "website:build",
"serverTarget": "website:server"
},
"configurations": {
"production": {
"browserTarget": "website:build:production",
"serverTarget": "website:server:production"
}
}
},
"prerender": {
"builder": "@nguniversal/builders:prerender",
"options": {
"browserTarget": "website:build:production",
"serverTarget": "website:server:production",
"routes": ["/"]
},
"configurations": {
"production": {}
}
}
}
}
}
}
構建完成后,將創建一個/dist文件夾,其結構如下:
dist/
└───website/
│ └───browser/
│ │ └───en/
│ │ └───fr/
│ └───server/
│ └───en/
│ └───fr/
在將 dist/website/browser 上傳到托管之前,我刪除了/dist/website/browser/en和/dist/website/browser/fr 中的 index.html 文件以確保托管服務於 https 功能(而不是索引.html 文件)。
最后,這是我對 firebase (firebase.json) 的配置:
{
...
"hosting": [
...
{
"target": "website",
"public": "dist/website/browser",
"ignore": ["firebase.json", "**/.*", "**/node_modules/**"],
"rewrites": [
{
"source": "**",
"function": "universal-globalSsr"
}
]
},
...
],
...
}
如前所述,一切都按預期構建、打包和部署。 一旦我嘗試訪問https://www.my-domaine.com/fr/ ,我的函數就會被執行,但我的日志中出現服務器超時,沒有任何錯誤。 如果我嘗試訪問不存在的 url(例如: https : //www.my-domaine.com/fr/foo ),我會收到錯誤“無法匹配任何路由。URL 段:'foo'”,然后超時。
在這一點上,我不知道我的代碼或/和我的項目配置有什么問題。
任何幫助將不勝感激。
對於那些在使用 Angular Universal 和 firebase 時,他們的服務器陷入無限加載狀態的人,我的問題來自我的應用程序中的特定 firestore 請求
在我的項目中,我將 @angular/fire 與 Rxjs 一起使用。 在應用程序初始化時,我在我的一項服務中發出請求以預緩存配置對象,類似於:
this.afs
.collection<MyObject>(this.cl.COLLECTION_NAME_OBJECT)
.snapshotChanges()
.pipe(
map((actions) =>
actions.map((a) => {
const data = a.payload.doc.data() as MyObject;
const id = a.payload.doc.ref;
return { id, ...data };
})
),
take(1)
)
.subscribe((objects: MyObjects[]) => {
this.myObjects = objects;
});
由於某種原因,管道中的take(1)
操作符負責保持服務器端。 刪除take(1)
解決了問題。
我發現了這個問題,其中某些特定類型的 firestore 請求正在破壞 ssr(有關此事的更多信息): https : //github.com/angular/angularfire/issues/2420
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.