运行时本地化模式
在 Lit Localize 运行时模式中,为每个语言环境生成一个 JavaScript 或 TypeScript 模块。每个生成的模块包含该语言环境的本地化模板。当您的应用程序切换语言环境时,将导入该语言环境的模块,并且所有本地化组件将重新渲染。
请参阅 输出模式 以比较 Lit Localize 的输出模式。
示例输出
永久链接到“示例输出”// locales/es-419.tsexport const templates = { h3c44aff2d5f5ef6b: html`Hola <b>Mundo!</b>`,};使用运行时模式的示例
永久链接到“使用运行时模式的示例”以下示例演示了一个使用 Lit Localize 运行时模式构建的应用程序
Lit GitHub 存储库包含完整的运行示例 (JavaScript, TypeScript) 的 Lit Localize 运行时模式,您可以将其用作模板。
配置运行时模式
永久链接到“配置运行时模式”在您的 lit-localize.json 配置文件中,将 output.mode 属性设置为 runtime,并将 output.outputDir 属性设置为您想要生成本地化模板模块的位置。请参阅 运行时模式设置 以了解更多详细信息。
接下来,将 output.localeCodesModule 设置为您选择的路径。Lit Localize 将在这里生成一个 .js 或 .ts 模块,它反映了您配置文件中的 sourceLocale 和 targetLocales 设置作为导出的变量。生成的模块将类似于以下内容
export const sourceLocale = 'en';export const targetLocales = ['es-419', 'zh-Hans'];export const allLocales = ['en', 'es-419', 'zh-Hans'];最后,在您的 JavaScript 或 TypeScript 项目中,调用 configureLocalization,并传递一个具有以下属性的对象
sourceLocale: string:由您生成的output.localeCodesModule模块导出的sourceLocale变量。targetLocales: string[]:由您生成的output.localeCodesModule模块导出的targetLocales变量。loadLocale: (locale: string) => Promise<LocaleModule>:加载本地化模板的函数。返回一个 promise,该 promise 解析为给定语言环境代码的生成的本地化模板模块。请参阅 加载语言环境模块的方法 以获取您可以在此处使用的函数示例。
configureLocalization 返回一个具有以下属性的对象
getLocale:返回活动语言环境代码的函数。如果新的语言环境已开始加载,则getLocale将继续返回以前的语言环境代码,直到新的语言环境加载完成。setLocale:开始将活动语言环境切换到给定代码的函数,并返回一个 promise,该 promise 在新的语言环境加载完成后解析。使用示例
例如
import {configureLocalization} from '@lit/localize';// Generated via output.localeCodesModuleimport {sourceLocale, targetLocales} from './generated/locale-codes.js';
export const {getLocale, setLocale} = configureLocalization({ sourceLocale, targetLocales, loadLocale: (locale) => import(`/locales/${locale}.js`),});自动重新渲染
永久链接到“自动重新渲染”要自动在每次活动语言环境切换时触发组件的重新渲染,请在编写 JavaScript 时在您的 constructor 中应用 updateWhenLocaleChanges 函数,或在编写 TypeScript 时将 @localized 装饰器应用到您的类。
import {LitElement, html} from 'lit';import {customElement} from 'lit/decorators.js';import {msg, localized} from '@lit/localize';
@customElement('my-element');@localized()class MyElement extends LitElement { render() { // Whenever setLocale() is called, and templates for that locale have // finished loading, this render() function will be re-invoked. return msg(html`Hello <b>World!</b>`); }}import {LitElement, html} from 'lit';import {msg, updateWhenLocaleChanges} from '@lit/localize';
class MyElement extends LitElement { constructor() { super(); updateWhenLocaleChanges(this); }
render() { // Whenever setLocale() is called, and templates for that locale have // finished loading, this render() function will be re-invoked. return msg(html`Hello <b>World!</b>`); }}customElements.define('my-element', MyElement);状态事件
永久链接到“状态事件”lit-localize-status 事件在每次语言环境切换开始、完成或失败时都会在 window 上触发。您可以使用此事件来
在您无法使用
@localized装饰器时重新渲染(例如,当直接使用 Litrender函数时)。在语言环境切换开始时立即渲染,即使它还没有完成加载(例如,加载指示器)。
执行其他与本地化相关的任务(例如,设置语言环境首选项 cookie)。
事件类型
永久链接到“事件类型”detail.status 字符串属性告诉您发生了哪种状态更改,可以是 loading、ready 或 error
- loading
新的语言环境已开始加载。
detail对象包含loadingLocale: string:已开始加载的语言环境的代码。
在第一个语言环境完成加载之前请求第二个语言环境的情况下,将调度一个新的
loading事件,并且不会为第一个请求调度任何ready或error事件。loading状态可以后跟ready、error或loading状态。- ready
新的语言环境已成功加载并可以进行渲染。
detail对象包含readyLocale: string:已成功加载的语言环境的代码。
ready状态只能后跟loading状态。- error
新的语言环境加载失败。
detail对象包含errorLocale: string:加载失败的语言环境的代码。errorMessage: string:语言环境加载失败的错误消息。
error状态只能后跟loading状态。
使用状态事件的示例
永久链接到“使用状态事件的示例”// Show/hide a progress indicator whenever a new locale is loading,// and re-render the application every time a new locale successfully loads.window.addEventListener('lit-localize-status', (event) => { const spinner = document.querySelector('#spinner');
if (event.detail.status === 'loading') { console.log(`Loading new locale: ${event.detail.loadingLocale}`); spinner.removeAttribute('hidden'); } else if (event.detail.status === 'ready') { console.log(`Loaded new locale: ${event.detail.readyLocale}`); spinner.setAttribute('hidden', ''); renderApplication(); } else if (event.detail.status === 'error') { console.error( `Error loading locale ${event.detail.errorLocale}: ` + event.detail.errorMessage ); spinner.setAttribute('hidden', ''); }});加载语言环境模块的方法
永久链接到“加载语言环境模块的方法”Lit Localize 允许您根据需要加载语言环境模块,因为您可以将任何函数作为 loadLocale 选项传递。以下是一些常见模式
延迟加载
永久链接到“延迟加载”使用 动态导入 仅在语言环境变为活动时才加载它。这是一种很好的默认方法,因为它最大程度地减少了用户将下载和执行的代码量。
import {configureLocalization} from '@lit/localize';import {sourceLocale, targetLocales} from './generated/locale-codes.js';
const {getLocale, setLocale} = configureLocalization({ sourceLocale, targetLocales, loadLocale: (locale) => import(`/locales/${locale}.js`),});预加载
永久链接到“预加载”在页面加载时开始预加载所有语言环境。动态导入仍然用于确保页面上的剩余脚本在获取语言环境模块时不会被阻止。
import {configureLocalization} from '@lit/localize';import {sourceLocale, targetLocales} from './generated/locale-codes.js';
const localizedTemplates = new Map( targetLocales.map((locale) => [locale, import(`/locales/${locale}.js`)]));
const {getLocale, setLocale} = configureLocalization({ sourceLocale, targetLocales, loadLocale: async (locale) => localizedTemplates.get(locale),});静态导入
永久链接到“静态导入”使用 静态导入 以一种阻止页面上其他脚本的方式预加载所有语言环境。
这种方法通常不建议使用,因为它会导致在页面上的其余脚本可以执行之前获取和执行比必要的更多代码,从而阻止交互性。仅当您的应用程序非常小、必须在单个 JavaScript 文件中分发或您有其他限制阻止使用动态导入时,才使用此方法。
import {configureLocalization} from '@lit/localize';import {sourceLocale, targetLocales} from './generated/locale-codes.js';
import * as templates_es_419 from './locales/es-419.js';import * as templates_zh_hans from './locales/zh-Hans.js';...
const localizedTemplates = new Map([ ['es-419', templates_es_419], ['zh-Hans', templates_zh_hans], ...]);
const {getLocale, setLocale} = configureLocalization({ sourceLocale, targetLocales, loadLocale: async (locale) => localizedTemplates.get(locale),});