SuperAPI AI 工具集

intlayer-preact

前端与建站

查看项目

更新于 10-15 17:23

技能介绍

用途:把 Intlayer 国际化方案接入 Preact 应用,适合需要在 Preact 项目中配置 i18n、创建已翻译组件的场景。核心理念是组件级内容声明,不使用庞大的全局翻译文件,而是在使用内容的 Preact 组件旁以 *.content.ts 文件就地声明。

主要能力:提供 useIntlayer 钩子读取字典内容,并支持多语言翻译声明。

使用方式:创建一个翻译组件需要两个文件。一是声明文件,例如 src/components/MyComponent/myComponent.content.ts,使用 intlayer 的 t() 和 Dictionary 类型定义字典,其中 key 必须唯一并与 useIntlayer() 传入的值一致: import { t, type Dictionary } from "intlayer"; const content = { key: "my-component", content: { text: t({ en: "Welcome", fr: "Bienvenue", es: "Hola" }) } } satisfies Dictionary; export default content;

二是实现文件,在 Preact 组件中从 preact-intlayer 引入 useIntlayer 钩子: import { useIntlayer } from "preact-intlayer"; const MyComponent = () => { const content = useIntlayer("my-component"); return (<div><h1>{content.text}</h1><img src={content.text.value} alt={content.text.value} /></div>); }; 其中直接返回内容用于文本节点,返回字符串时使用 .value。

适用场景:Preact 配合 Vite 的项目、需要按组件组织多语言文案的前端应用。

限制:本次资料未提供安装命令、具体版本要求、支持的完整语言列表以及除 Vite 外的构建工具配置细节,暂未提供。