【问题标题】:Angular Universal SSR with i18n not loading locale from server side带有 i18n 的 Angular Universal SSR 未从服务器端加载语言环境
【发布时间】:2021-10-15 20:25:01
【问题描述】:

我将 i18n 与 Angular Universal SSR 一起使用。问题是客户端收到源语言环境中的文本,几秒钟后被正确的语言环境替换。

例如,客户端加载 http://localhost:4000/en-US/ 在第一次显示中显示为 es 语言环境,几秒钟后文本为替换为 en-US 语言环境文本。

构建文件夹已正确创建,并且代理适用于每个区域设置。我希望服务器返回带有正确翻译的 html,以便 SEO 爬虫可以在每个语言环境中正确找到内容。

似乎问题出在构建中,不是使用正确的语言环境生成的。

angular.json 文件中的项目配置:

...
"i18n": {
   "sourceLocale": "es",
   "locales": {
     "en-US": {
      "translation":"src/i18n/messages.en.xlf",
      "baseHref": "en-US/"
     }
 }
},
...
"architect": {
        "build": {
          "builder": "@angular-builders/custom-webpack:browser",
          "options": {
            "outputPath": "dist/web/browser",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.app.json",
            "aot": true,
            "localize": true,
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "src/styles.scss"
            ],
            "scripts": [], 
            "customWebpackConfig":{
              "path": "./webpack.config.js"
            }
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "namedChunks": false,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true,
              "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "2mb",
                  "maximumError": "5mb"
                },
                {
                  "type": "anyComponentStyle",
                  "maximumWarning": "2kb",
                  "maximumError": "4kb"
                }
              ]
            }
          },
         ...
    }

构建项目的命令:

ng build --prod --configuration=production && ng run web:server:production

构建目录导致路径dist/web/browser

en-US/
es/
                    

server.ts文件:

export function app(lang: string): express.Express {
  const server = express();
  server.use(compression());
  const distFolder = join(process.cwd(), `dist/web/browser/${lang}`);
  const indexHtml = 'index.html';


  // Our Universal express-engine (found @ https://github.com/angular/universal/tree/master/modules/express-engine)
  server.engine('html', ngExpressEngine({
    bootstrap: AppServerModule,
    extraProviders: [{ provide: LOCALE_ID, useValue: lang }],
  } as any));

  server.set('view engine', 'html');
  server.set('views', distFolder);

  server.get('*.*', express.static(distFolder, {
    maxAge: '1y'
  }));

  server.get('*', (req, res) => {
    console.log(`LOADING DIST FOLDER: ${distFolder}`)
    console.log(`LOADING INDEX: ${indexHtml}`)
    res.render(`${indexHtml}`, {
      req,
      res,
      providers: [
        { provide: APP_BASE_HREF, useValue: req.baseUrl },
        { provide: NgxRequest, useValue: req },
        { provide: NgxResponse, useValue: res }
        ]
    });
  });

  return server;
}

function run(): void {
  const port = process.env.PORT || 4000;

  // Start up the Node server
  const server = express();
  const appEs = app('es');
  const appEn = app('en-US');
  server.use('/en-US', appEn);
  server.use('/es', appEs);
  server.use('', appEs);

  server.use(compression());
  server.use(cookieparser());
  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')) {
  run();
}

export * from './src/main.server';

【问题讨论】:

    标签: angular server-side-rendering angular-i18n


    【解决方案1】:

    默认情况下,服务器可能首先提供静态文件。要解决这个问题,您应该在 dist 文件夹中将 index.html 的名称更改为 index.origial.html。

    在您的server.ts 文件中

      // check for the correct version
      const indexHtml = existsSync(join(distFolder, 'index.original.html'))
        ? 'index.original.html'
        : 'index.html';
    

    因此结果将是您的 'es' 版本随后被称为 index.original.html 并且辅助版本将成为 index.html 中的新静态版本将首先提供。

    【讨论】:

    • 它没有用。我在 dist/web/browser/es 和 dist/web/browser/en-US 两个目录中将 index.html 重命名为 index.original.html,并添加了该行以检查正确的版本。我不太了解这个解决方案,你能详细解释一下吗?
    【解决方案2】:

    经过一些研究,我找到了最佳解决方案。为了使服务器发送带有正确翻译的视图,您需要添加一个代理文件并为每个语言环境创建服务器。

    为本地化标志为 true 的服务器启用 i18n:

    "server": {
              "builder": "@angular-devkit/build-angular:server",
              "options": {
                "outputPath": "dist/web/server",
                "main": "server.ts",
                "tsConfig": "tsconfig.server.json"
              },
              "configurations": {
                "production": {
                  "outputHashing": "media",
                  "fileReplacements": [
                    {
                      "replace": "src/environments/environment.ts",
                      "with": "src/environments/environment.prod.ts"
                    }
                  ],
                  "sourceMap": false,
                  "optimization": true,
                  "localize": true
                }
            },
    

    创建proxy-server.js:

    const express = require("express");
    const path = require("path");
    
    const getTranslatedServer = (lang) => {
      const distFolder = path.join(
        process.cwd(),
        `dist/web/server/${lang}`
      );
      const server = require(`${distFolder}/main.js`);
      return server.app(lang);
    };
    
    function run() {
      const port = 4000;
    
      // Start up the Node server
      const appEs = getTranslatedServer("/es");
      const appEn = getTranslatedServer("/en");
    
      const server = express();
    
      server.use("/es", appEs);
      server.use("/en", appEn);
      server.use("", appEs);
    
      server.listen(port, () => {
        console.log(`Node Express server listening on http://localhost:${port}`);
      });
    }
    
    run();
    

    server.ts:

    import '@angular/localize/init';
    import 'zone.js/dist/zone-node';
    
    import { ngExpressEngine } from '@nguniversal/express-engine';
    
    import * as express from 'express';
    import { join } from 'path';
    import * as cookieparser from 'cookie-parser';
    
    const path = require('path');
    const fs = require('fs');
    const domino = require('domino');
    const templateA = fs.readFileSync(path.join('dist/web/browser/en', 'index.html')).toString();
    
    const { provideModuleMap } = require('@nguniversal/module-map-ngfactory-loader');
    
    const compression = require('compression');
    
    const win = domino.createWindow(templateA);
    win.Object = Object;
    win.Math = Math;
    
    global.window = win;
    global.document = win.document;
    global.Event = win.Event;
    global.navigator = win.navigator;
    console.log('declared Global Vars....');
    
    
    
    import { AppServerModule } from './src/main.server';
    import { NgxRequest, NgxResponse } from 'ngxc-universal';
    import { environment } from 'src/environments/environment';
    import { LOCALE_ID } from '@angular/core';
    
    const PORT = process.env.PORT || 4000;
    const DIST_FOLDER = join(process.cwd(), 'dist/web');
    
    const {LAZY_MODULE_MAP} = require('./src/main.server');
    
    
    
    
    
    export function app(lang: string){
      const localePath =  'browser' + lang;
    
      const server = express();
      server.use(compression());
      server.use(cookieparser());
      server.set('view engine', 'html');
      server.set('views', join(DIST_FOLDER, 'browser' + lang));
    
      server.get('*.*', express.static(join(DIST_FOLDER, localePath), {
        maxAge: '1y'
      }));
    
      server.engine('html', ngExpressEngine({
        bootstrap: AppServerModule,
        providers: [
          provideModuleMap(LAZY_MODULE_MAP),
          {provide: LOCALE_ID, useValue: lang}
        ]
      }));
    
      server.get('*', (req, res) => {
        res.render(`index`, {
          req,
          res,
          providers: [
            { provide: NgxRequest, useValue: req },
            { provide: NgxResponse, useValue: res }
            ]
        });
      });
    
    
      return server;
    
    }
    
    
    function run() {
      const server = express();
      const appEn = app('/en');
      const appES = app('/es');
    
      server.use('/en', appEn);
      server.use('/', appES);
    
    
    
      server.listen(PORT, () => {
          console.log(`Node Express server listening on http://localhost:${PORT}`);
      });
    }
    declare const __non_webpack_require__: NodeRequire;
    const mainModule = __non_webpack_require__.main;
    const moduleFilename = (mainModule && mainModule.filename) || '';
    if ( (!environment.production && moduleFilename === __filename) ||
      moduleFilename.includes('iisnode')
    ) {
      run();
    }
    
    export * from './src/main.server';
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-27
      • 2021-11-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-07
      • 1970-01-01
      • 2021-12-23
      • 2021-02-12
      相关资源
      最近更新 更多