Angular 2+ localization (i18n) rtl support

前端 未结 3 1440
时光说笑
时光说笑 2020-12-31 19:54

What is the best practice for adding right to left (rtl) support into a localized Angular 2+ app (e.g. for Hebrew and Arabic languages)? I looked through several tutorials i

3条回答
  •  自闭症患者
    2020-12-31 20:49

    The problem is the main index.html (and some other files) isn't a template and you can't do some stuff with it (e. g. translation). See this issue.

    But because it is an easy process, I tried to do it myself:

    1. Create a translated version of your main index.html and insert it in a folder that named the code of your rtl language (fa in my case):

      src/fa/index.html:

      
      
      
          
          عنوان برنامه
          
      
          
          
          
          
      
          
       
      
      
      
      
      
      
      

      Especially see lang="fa" and dir="rtl" and native texts.

    2. In the related build configurations (in my case: production-fa and fa) in your angular.json file put:

      "index": "src/fa/index.html"
      

    Done.


    You can do same with other languages (Even ltrs! Because of other changes that we made in index.html).

    To better understanding I also insert related build scripts in my package.json file:

        "start-fa": "ng serve --configuration=fa",
        "build-fa": "ng build --configuration=fa",
        "build-prod-fa": "ng build --prod --configuration=production-fa",
    

    Bonus: What about manifest.json file (in case you want an installable PWA)?

    The first step like above. Create a translated version in src/fa/manifest.json:

    {
        "dir": "rtl",
        "lang": "fa",
        "name": "نام بلند برنامه",
        "short_name": "نام کوتاه",
        "theme_color": ...
        ...
    

    But the second step is a little more difficult. I couldn't find a way to define its path. You can replace the original (src/manifest.json) with this one. You must do it BEFORE the build process starts (not after it by replacing dist/.../manifest.json; because @angular/service-worker needs to know its final state during the build process). So in your package.json:

    "build-prod-fa": "cp src/fa/manifest.json src/manifest.json && ng build --prod --configuration=production-fa",
    

    And revert it to its default version (in my case the default language is en) before the default production build:

    "build-prod": "cp src/en/manifest.json src/manifest.json && ng build --prod",
    

    Note that about manifest.json just production builds are important. Because serviceWorker is enabled only in these configurations by default (see your angular.json file).


    I know this is not an ideal solution. Because you will need to edit your sources (in these two files) in multiple places.

提交回复
热议问题