This is the first day of my participation in the Gwen Challenge in November. Check out the details: the last Gwen Challenge in 2021

The author recently took over the company’s international development needs, and spent a lot of time investigating a set of international implementation plans. I have to be careful and share with you.

This article focuses only on one of the small points of internationalization, “load language packs on demand”.

What is front-end internationalization?

The so-called front-end internationalization is to calculate a language that the website can support according to the user’s language Settings and browser environment, and then replace the website’s copy with the corresponding language copy.

Solutions are:

  1. For different languages, package into different project compilation packages, internationalization in the compilation process;

  2. Use a project that maps the final text by ID and language, internationalization at run time;

In the first scenario, the compiled HTML for the corresponding language is returned when the user requests the page. Specific development operations, in fact, is to copy the project, the language inside to another language, maintenance is more trouble, only suitable for some relatively simple static pages.

Or I could use a packaging tool to package multiple build packages, but I didn’t find any concrete solutions that would work, and my gut feeling was that this would be difficult to test, locate bugs, and maintain, without doing much in-depth research.

The second, more mainstream, is to determine the language while the script is running, and then get the copy with the ID and render it on the page.

The id to copy mapping needs to be saved as follows:

const locale = {
  'zh-CN': {
    hello: 'hello'.thank: 'thank you'.steamedBuns: 'Xiao long bao'.goodbye: 'goodbye'}}Copy the code

However, it is more common to use JSON files and place json from different languages in a locale directory:

projectRoot
|-- lang
|   |-- en-US.json
|   |-- fr.json
|   |-- zh-CN.json
Copy the code

We then use the corresponding language package in the business code, and get the copy by ID where it is used. React, for example, can be used like this:

<div>{ intl.formatMessage({ id: 'hello' }) }</div>
/ / rendering for
<div>hello</div>
Copy the code

Why do you need to load language packs on demand?

Loading language packages on demand means loading only the language packages used, rather than loading all the language packages at once.

The language package of a single language is already very large, and the size of the language package will increase with the increasing number of pages and copywriting on the website. For example, in the project I worked on, a single language package without compression was about 500 lines and a file size of about 300K, and more.

If you do full load instead of on demand, each additional language adds 300K to the file. For every additional copy, you add n lines of content. There’s no need.

Load on demand solutions

Scenario 1: The HTML returned from the back end is directly attached to the language pack script

Python < python style = “box-sizing: border-box; color: RGB (74, 74, 74); display: block; line-height: 22px; font-size: 14px! Important; white-space: inherit! Important;”

<script id="messages" type="application/json" data-locale="ko-KR">
  {"FrontPricingPage.individualSection.header":"개 original spelling 용". } </script>Copy the code

Parse (document.getelementByID (‘messages’).innertext) to retrieve the package object.

Alternatively, you can embed a script with window.tti18n = XXX, which has the same effect, but without the JSON to object conversion.

The point here is that the back end calculates the user’s language once the page is requested. This can be determined by the ACCEPt-language (user-agent) and User information of the HTTP request header, and then the corresponding Language package is pieced into HTML to return. The specific logic is:

  • The user has not set the language= = >Accept-Language as the first weight Language; User-agent is used to handle specific clients (such as the staple browser)= = >If there is no counterpart for the language, the back-pocket language pack, usually English, is used= = >Calculate the end
  • The user sets the language= = >The end of the

Disadvantages:

  • You can’t take advantage of caching, HTML doesn’t normally do caching;
  • There are docking costs and communication costs in front and back end coordination;
  • Language package content is more, spell to HTML consumption server resources;

Scenario 2: The front-end imports the language package through dynamic import

The template returned from the back end is filled with the language set by the user. You need to spell it into HTML, such as the locale property of the global useInfo object. Without HTML, the front end will need to request an interface for the user’s language Settings, which is not necessary.

It is then combined with the navigator.language to get the final language. Of course, this step can also be handled by the back end. In scenario 1, the back end uses HTTP request header fields to calculate.

The loaded language package can then be exposed to the global environment and initialized to render React, or injected into the React component through the Context (react-intl).

Example:

The zh-cn. Json file in the locale directory

{
  "hello": "Hello"."thank": "Thank you"."steamedBuns": "Xiao long bao"."goodbye": "Goodbye"
}
Copy the code

React entry file

import(
  /* webpackChunkName: "lang" */
  `./locale/${lang}.json`
).then(m= > {
  window.TTi18n = m.default;
  ReactDOM.render(/ *... * /);
})
Copy the code

If you’re using WebPack, webPack parses the code and packages each JSON file in the locale directory into a separate module file. I used magic comments in the code to specify the name of the module file as lang, so the file name format for the final package will look like this: lang0.90dfe781.chunk.js, lang1.fe9ff131.chunk.js.

Webpack adds hashes to these files, and the files make good use of the cache if their contents do not change. When the content is updated, the file name changes, the cache is not removed, and the browser gets the latest language pack.

Webpack dynamically imports official documents

In general, I think the second approach, namely dynamic import, is more suitable for loading language packages on demand. The downside is that you need to request the language pack more than once, but it’s not really a downside because you can effectively use the cache.

reading

  • Webnovel Internationalization Practice – Zhihu column
  • Webpack Magic notes official documentation
  • Webpack dynamically imports official documents