変換ローカライゼーションモード
Lit Localizeの変換モードでは、ロケールごとに個別のフォルダが生成されます。各フォルダには、そのロケールでアプリケーションの完全なスタンドアロンビルドが含まれており、すべての実行時`@lit/localize`コードが削除されています。
- `msg`呼び出しは、各ロケールで静的にローカライズされた文字列またはテンプレートのバージョンに置き換えられます。
- `str`タグは削除されます。
- `@lit/localize`のインポートは削除されます。
- テンプレートは、可能な限り親テンプレートに折りたたむことで、不要な式を削除するように最適化されます。
例えば、ソースが以下の場合
// src/launch-button.js
import {msg} from '@lit/localize';
render() {
return html`<button>${msg('Launch rocket')}</button>`
}
以下のファイルが生成されます
// locales/en/launch-button.js
render() {
return html`<button>Launch rocket</button>`
}
// locales/es-419/launch-button.js
render() {
return html`<button>Lanza cohete</button>`
}
変換モードの設定
「変換モードの設定」へのパーマリンク`lit-localize.json`設定ファイルで、`mode`プロパティを`transform`に設定し、`output.outputDir`プロパティをローカライズされたアプリケーションフォルダを生成する場所に設定します。詳細については、変換モードの設定を参照してください。
JavaScriptまたはTypeScriptプロジェクトで、必要に応じて`configureTransformLocalization`を呼び出し、以下のプロパティを持つオブジェクトを渡します。
- `sourceLocale: string`:ソーステンプレートが記述されているロケール。ロケールコードとして指定します(例:`"en"`)。
`configureTransformLocalization`は、以下のプロパティを持つオブジェクトを返します。
- `getLocale`:アクティブなロケールコードを返す関数。
例:
import {configureTransformLocalization} from '@lit/localize';
export const {getLocale} = configureTransformLocalization({
sourceLocale: 'en',
});
初期ロケールの設定
「初期ロケールの設定」へのパーマリンク変換モードでは、アクティブなロケールはロードするJavaScriptバンドルによって決定されます。ページの読み込み時にどのバンドルを読み込むかを決定する方法は、ユーザー次第です。
たとえば、アプリケーションのロケールがURLパスに反映されている場合は、URLをチェックして適切な`<script>`タグを挿入するインラインスクリプトをHTMLファイルに含めることができます。
スクリプト名を動的に選択する場合は、常にロケールコードを検証してください。以下の例は、既知のロケールコードのいずれかと一致する場合にのみスクリプトを読み込むことができるため安全ですが、一致ロジックの精度が低い場合は、安全でないJavaScriptを挿入するバグまたは攻撃が発生する可能性があります。
import {allLocales} from './generated/locales.js';
const url = new URL(window.location.href);
const unsafeLocale = url.searchParams.get('locale');
const locale = allLocales.includes(unsafeLocale) ? unsafeLocale : 'en';
const script = document.createElement('script');
script.type = 'module';
script.src = `/${locale}.js`;
document.head.appendChild(script);
パフォーマンスを向上させるために、サーバー上のHTMLファイルに適切なスクリプトタグを静的にレンダリングできます。これにより、ブラウザはできるだけ早くスクリプトのダウンロードを開始できます。
ロケールの切り替え
「ロケールの切り替え」へのパーマリンク変換モードでは、`setLocale`関数は使用できません。代わりに、ページをリロードして、次回の読み込みで別のロケールバンドルが選択されるようにします。
たとえば、この`locale-picker`カスタム要素は、ドロップダウンリストから新しいロケールが選択されるたびに新しいURLを読み込みます。
import {LitElement, html} from 'lit';
import {customElement} from 'lit/decorators.js';
import {getLocale} from './localization.js';
import {allLocales} from './generated/locales.js';
@customElement('locale-picker');
export class LocalePicker extends LitElement {
render() {
return html`
<select @change=${this.localeChanged}>
${allLocales.map(
(locale) =>
html`<option value=${locale} selected=${locale === getLocale()}>
${locale}
</option>`
)}
</select>
`;
}
localeChanged(event: Event) {
const newLocale = (event.target as HTMLSelectElement).value;
const url = new URL(window.location.href);
if (url.searchParams.get('locale') !== newLocale) {
url.searchParams.set('locale', newLocale);
window.location.assign(url.href);
}
}
}
import {LitElement, html} from 'lit';
import {getLocale} from './localization.js';
import {allLocales} from './generated/locales.js';
export class LocalePicker extends LitElement {
render() {
return html`
<select @change=${this.localeChanged}>
${allLocales.map(
(locale) =>
html`<option value=${locale} selected=${locale === getLocale()}>
${locale}
</option>`
)}
</select>
`;
}
localeChanged(event) {
const newLocale = event.target.value;
const url = new URL(window.location.href);
if (url.searchParams.get('locale') !== newLocale) {
url.searchParams.set('locale', newLocale);
window.location.assign(url.href);
}
}
}
customElements.define('locale-picker', LocalePicker);
Rollupとの統合
「Rollupとの統合」へのパーマリンクRollupを使用していて、`lit-localize build`コマンドを個別に実行する代わりに統合ソリューションを希望する場合は、`@lit/localize-tools/lib/rollup.js`から`localeTransformers`関数をRollup設定にインポートします。
この関数は、`{locale, transformer}`オブジェクトの配列を生成します。これは、@rollup/plugin-typescriptのtransformersオプションと組み合わせて使用して、ロケールごとに個別のバンドルを生成できます。
JavaScriptを記述する場合、ここで使用されているTypeScriptコンパイラについて心配する必要はありません。 Lit Localizeは、ソースコードを解析、分析、および変換するためにTypeScriptコンパイラに依存していますが、プレーンJavaScriptファイルも処理します。
次の`rollup.config.mjs`は、各ロケールの縮小バンドルを`./bundled/<locale>/`ディレクトリに生成します。
import typescript from '@rollup/plugin-typescript';
import {localeTransformers} from '@lit/localize-tools/lib/rollup.js';
import resolve from '@rollup/plugin-node-resolve';
import {terser} from 'rollup-plugin-terser';
// Config is read from ./lit-localize.json by default.
// Pass a path to read config from another location.
const locales = localeTransformers();
export default locales.map(({locale, localeTransformer}) => ({
input: `src/index.ts`,
plugins: [
typescript({
transformers: {
before: [localeTransformer],
},
}),
resolve(),
terser(),
],
output: {
file: `bundled/${locale}/index.js`,
format: 'es',
},
}));
import typescript from '@rollup/plugin-typescript';
import resolve from '@rollup/plugin-node-resolve';
import {terser} from 'rollup-plugin-terser';
import summary from 'rollup-plugin-summary';
import {localeTransformers} from '@lit/localize-tools/lib/rollup.js';
// Config is read from ./lit-localize.json by default.
// Pass a path to read config from another location.
const locales = localeTransformers();
export default locales.map(({locale, localeTransformer}) => ({
input: `src/index.js`,
plugins: [
typescript({
transformers: {
before: [localeTransformer],
},
// Specifies the ES version and module format to emit. See
// https://typescript.dokyumento.jp/docs/handbook/tsconfig-json.html
tsconfig: 'jsconfig.json',
// Temporary directory where transformed modules will be emitted before
// Rollup bundles them.
outDir: 'bundled/temp',
// @rollup/plugin-typescript always matches only ".ts" files, regardless
// of any settings in our jsconfig.json.
include: ['src/**/*.js'],
}),
resolve(),
terser(),
summary({
showMinifiedSize: false,
}),
],
output: {
file: `bundled/${locale}/index.js`,
format: 'es',
sourcemap: true,
},
}));