I18n 生命周期
外掛使用這些生命週期加載 I18n 相關的資料。
getTranslationFiles({content})
外掛宣告他們想要使用的 JSON 翻譯檔案。
傳回翻譯檔案 {path: 字串, content: ChromeI18nJSON}
path
:外掛語言資料夾的相對路徑i18n/[語言]/[外掛名稱]
。副檔名.json
應省略以保持泛用性。content
:使用 Chrome I18n JSON 格式。
這些檔案會由 write-translations
CLI 寫入外掛 i18n 子檔案夾,然後會在呼叫 translateContent()
和 translateThemeConfig()
之前,以適當的語言讀取。
範例
my-plugin.js
export default function (context, options) {
return {
name: 'my-plugin',
async getTranslationFiles({content}) {
return [
{
path: 'sidebar-labels',
content: {
someSidebarLabel: {
message: 'Some Sidebar Label',
description: 'A label used in my plugin in the sidebar',
},
someLabelFromContent: content.myLabel,
},
},
];
},
};
}
translateContent({content,translationFiles})
使用語言資料夾的翻譯檔案來翻譯外掛內容。
傳回語言資料夾的外掛內容。
contentLoaded()
生命周期會使用 translateContent()
傳回來的語言資料夾外掛內容來呼叫。
範例
my-plugin.js
export default function (context, options) {
return {
name: 'my-plugin',
translateContent({content, translationFiles}) {
const myTranslationFile = translationFiles.find(
(f) => f.path === 'myTranslationFile',
);
return {
...content,
someContentLabel: myTranslationFile.someContentLabel.message,
};
},
};
}
translateThemeConfig({themeConfig,translationFiles})
使用在地化的翻譯檔案,翻譯網站的 themeConfig
標籤。
傳回在地化的 themeConfig
。
範例
my-plugin.js
export default function (context, options) {
return {
name: 'my-theme',
translateThemeConfig({themeConfig, translationFiles}) {
const myTranslationFile = translationFiles.find(
(f) => f.path === 'myTranslationFile',
);
return {
...themeConfig,
someThemeConfigLabel: myTranslationFile.someThemeConfigLabel.message,
};
},
};
}
async getDefaultCodeTranslationMessages()
使用 <Translate>
API 的主題可以提供預設的程式碼翻譯訊息。
它應傳回 Record<string, string>
中的訊息,其中鍵是翻譯 ID,而值是訊息(不包括說明),使用網站的目前區域設定在地化。
範例
my-plugin.js
export default function (context, options) {
return {
name: 'my-theme',
async getDefaultCodeTranslationMessages() {
return readJsonFile(`${context.i18n.currentLocale}.json`);
},
};
}