استخدم مساعدك المفضل للملخص واستخدم هذه الصفحة والموفر AI الذي تريده
تاريخ الإصدارات
- "تحديث استخدام واجهة برمجة تطبيقات useIntlayer في Solid للوصول المباشر إلى الخصائص"v8.9.04/5/2026
- "التوثيق الأولي لـ Astro + Vanilla JS"v8.7.724/4/2026
تمت ترجمة محتوى هذه الصفحة باستخدام الذكاء الاصطناعي.
اعرض آخر نسخة المحتوى الأصلي باللغة الإنكليزيةإذا كان لديك فكرة لتحسين هذه الوثيقة، فلا تتردد في المساهمة من خلال تقديم طلب سحب على GitHub.
رابط GitHub للتوثيقنسخ الـ Markdown من المستند إلى الحافظة
ترجمة موقع Astro + Vanilla JS الخاص بك باستخدام Intlayer | التدويل (i18n)
جدول المحتويات
ما هو Intlayer؟
Intlayer هي مكتبة تدويل (i18n) مبتكرة ومفتوحة المصدر مصممة لتبسيط دعم اللغات المتعددة في تطبيقات الويب الحديثة.
باستخدام Intlayer، يمكنك:
- إدارة الترجمات بسهولة: باستخدام قواميس تعريفية على مستوى المكون.
- توطين الميتا داتا والمسارات والمحتوى ديناميكيًا.
- ضمان دعم TypeScript: من خلال أنواع مولدة تلقائيًا لتعزيز الإكمال التلقائي واكتشاف الأخطاء.
- الاستفادة من الميزات المتقدمة: مثل الكشف الديناميكي عن اللغة وتبديل اللغة.
دليل خطوة بخطوة لتهيئة Intlayer في Astro + Vanilla JS
تحقق من نموذج التطبيق على GitHub.
الخطوة 1: تثبيت التبعيات
قم بتثبيت الحزم اللازمة باستخدام مدير الحزم المفضل لديك:
نسخ الكود إلى الحافظة
npm install intlayer astro-intlayer vanilla-intlayernpx intlayer initintlayer الحزمة الأساسية التي توفر أدوات i18n لإدارة التكوين، الترجمات، تعريف المحتوى، التحويل، وأوامر CLI.
astro-intlayer تتضمن إضافة تكامل Astro لربط Intlayer بـ Vite bundler، بالإضافة إلى وسيط (middleware) لاكتشاف لغة المستخدم المفضلة، وإدارة ملفات تعريف الارتباط (cookies)، والتعامل مع إعادة توجيه الروابط.
vanilla-intlayer حزمة لدمج Intlayer في تطبيقات Vanilla JavaScript / TypeScript. توفر كائن Pub/Sub أحادي (
IntlayerClient) ومساعدين يعتمدون على الاستدعاءات (useIntlayer,useLocale, إلخ)، مما يسمح لأي جزء من وسوم<script>في Astro بالاستجابة لتغييرات اللغة دون الحاجة إلى إطار عمل واجهة مستخدم.
الخطوة 2: تهيئة مشروعك
أنشئ ملف تكوين لتحديد لغات تطبيقك:
نسخ الكود إلى الحافظة
import { Locales, type IntlayerConfig } from "intlayer";const config: IntlayerConfig = { internationalization: { locales: [ Locales.ENGLISH, Locales.FRENCH, Locales.SPANISH, Locales.ARABIC, // لغاتك الأخرى ], defaultLocale: Locales.ENGLISH, },};export default config;من خلال ملف التكوين هذا، يمكنك تهيئة الروابط المترجمة، وإعادة توجيه الوسيط، وأسماء الكوكيز، وموقع وامتدادات تعريفات المحتوى، وتعطيل سجلات Intlayer في وحدة التحكم، والمزيد. للحصول على قائمة كاملة بالمعلمات المتاحة، راجع توثيق التهيئة.
الخطوة 3: دمج Intlayer في تكوين Astro الخاص بك
أضف إضافة intlayer إلى تكوين Astro الخاص بك. بالنسبة لـ Vanilla JS، لا يلزم وجود تكامل إضافي لإطار عمل واجهة مستخدم.
نسخ الكود إلى الحافظة
// @ts-checkimport { intlayer } from "astro-intlayer";import { defineConfig } from "astro/config";// https://astro.build/configexport default defineConfig({ integrations: [intlayer()],});تُستخدم إضافة intlayer() لدمج Intlayer مع Astro. وهي تضمن إنشاء ملفات تعريف المحتوى ومراقبتها في وضع التطوير. وتعرّف متغيرات بيئة Intlayer داخل تطبيق Astro وتوفر أسماء مستعارة لتحسين الأداء.
الخطوة 4: تعريف المحتوى الخاص بك
أنشئ وأدِر تعريفات المحتوى لتخزين الترجمات:
نسخ الكود إلى الحافظة
import { t, type Dictionary } from "intlayer";const appContent = { key: "app", content: { greeting: t({ en: "Hello World", fr: "Bonjour le monde", es: "Hola mundo", ar: "مرحبا بالعالم", }), description: t({ en: "Welcome to my multilingual Astro site.", fr: "Bienvenue sur mon site Astro multilingue.", es: "Bienvenido a mi sitio Astro multilingüe.", ar: "مرحبا بكم في موقع Astro متعدد اللغات الخاص بي.", }), switchLocale: t({ en: "Switch language:", fr: "Changer de langue :", es: "Cambiar idioma:", ar: "تغيير اللغة:", }), },} satisfies Dictionary;export default appContent;يمكن تعريف تعريفات المحتوى في أي مكان في تطبيقك، طالما أنها مدرجة فيcontentDir(افتراضيًا./src) وتطابق امتداد ملف تعريف المحتوى (افتراضيًا.content.{json,ts,tsx,js,jsx,mjs,cjs}).
لمزيد من المعلومات، راجع توثيق تعريف المحتوى.
الخطوة 5: استخدام المحتوى في Astro
مع Vanilla JS، يتم إجراء جميع عمليات الرندر في جانب الخادم مباشرة داخل ملفات .astro باستخدام getIntlayer. بعد ذلك، تقوم كتلة <script> بتهيئة vanilla-intlayer على العميل لتمكين تبديل اللغة.
نسخ الكود إلى الحافظة
---import { getIntlayer, getLocaleFromPath, getLocalizedUrl, getPrefix, getLocaleName, localeMap, locales, defaultLocale, getPathWithoutLocale, type LocalesValues,} from "intlayer";export const getStaticPaths = () => { return localeMap(({ locale }) => ({ params: { locale: getPrefix(locale).localePrefix }, }));};const locale = getLocaleFromPath(Astro.url.pathname) as LocalesValues;const pathWithoutLocale = getPathWithoutLocale(Astro.url.pathname);const { greeting, description, switchLocale } = getIntlayer("app", locale);---<!doctype html><html lang={locale} dir={locale === 'ar' ? 'rtl' : 'ltr'}> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width" /> <link rel="icon" type="image/svg+xml" href="/favicon.svg" /> <title>{greeting}</title> <!-- رابط canonical --> <link rel="canonical" href={new URL(getLocalizedUrl(Astro.url.pathname, locale), Astro.site)} /> <!-- روابط Hreflang --> { localeMap(({ locale: mapLocale }) => ( <link rel="alternate" hreflang={mapLocale} href={new URL( getLocalizedUrl(Astro.url.pathname, mapLocale), Astro.site )} /> )) } <link rel="alternate" hreflang="x-default" href={new URL( getLocalizedUrl(Astro.url.pathname, defaultLocale), Astro.site )} /> </head> <body> <main> <h1 id="greeting">{greeting}</h1> <p id="description">{description}</p> <div class="locale-switcher"> <span class="switcher-label">{switchLocale}</span> <div class="locale-buttons"> { locales.map((localeItem) => ( <a href={localeItem === locale ? undefined : getLocalizedUrl(pathWithoutLocale, localeItem)} class={`locale-btn ${localeItem === locale ? "active" : ""}`} data-locale={localeItem} aria-disabled={localeItem === locale} > {getLocaleName(localeItem)} </a> )) } </div> </div> </main> </body></html>إذا كنت ترغب في استخدام محتواك في سمةسلسلة(string)، مثلaltوtitleوhrefوaria-labelوما إلى ذلك، يمكنك استخدام قيمة الدالة، مثل:
htmlنسخ الكودنسخ الكود إلى الحافظة
<img src="{content.image.src.value}" alt="{content.image.value}" /><img src="{content.image.src.toString()}" alt="{content.image.toString()}" /><img src="{String(content.image.src)}" alt="{String(content.image)}" />
ملاحظة حول إعداد التوجيه: تعتمد بنية الدليل التي تستخدمها على إعداد
middleware.routingفيintlayer.config.ts:
prefix-no-default(افتراضي): يحافظ على اللغة الافتراضية في الجذر (بدون بادئة) ويضيف بادئات للغات الأخرى. استخدم[...locale]لتغطية جميع الحالات.prefix-all: تحصل جميع الروابط على بادئة لغة. يمكنك استخدام[locale]القياسي إذا كنت لا تحتاج إلى معالجة الجذر بشكل منفصل.search-paramأوno-prefix: لا يلزم وجود أدلة لغة. يتم التعامل مع اللغة عبر معلمات الاستعلام أو ملفات تعريف الارتباط.
الخطوة 6: إضافة تبديل اللغة
في Astro مع Vanilla JS، يتم رندر مبدل اللغة على الخادم كروابط عادية ويتم تفعيله (hydrated) على العميل عبر كتلة <script>. عندما ينقر المستخدم على رابط لغة، يقوم vanilla-intlayer بتعيين كوكيز اللغة عبر setLocale قبل الانتقال إلى الرابط المترجم.
نسخ الكود إلى الحافظة
<!-- تضمين كود الخادم من الخطوة 5 أعلاه --><script> import { installIntlayer, useLocale } from "vanilla-intlayer"; import { getLocaleFromPath, getLocalizedUrl, type LocalesValues } from "intlayer"; // تهيئة Intlayer على العميل باللغة المأخوذة من المسار الحالي const locale = getLocaleFromPath(window.location.pathname); installIntlayer({ locale: locale as LocalesValues }); const { setLocale } = useLocale({ onLocaleChange: (newLocale: LocalesValues) => { window.location.href = getLocalizedUrl(window.location.pathname, newLocale); }, }); // ربط أحداث النقر بروابط تبديل اللغة const localeLinks = document.querySelectorAll("[data-locale]"); localeLinks.forEach((link) => { link.addEventListener("click", (e) => { const localeValue = link.getAttribute("data-locale") as LocalesValues; if (localeValue && localeValue !== locale) { e.preventDefault(); setLocale(localeValue); } }); });</script>ملاحظة حول الاستمرارية: تقوم
installIntlayerبتهيئة كائن Intlayer الأحادي باللغة المحددة من الخادم. وتضمنuseLocaleمعonLocaleChangeتعيين كوكيز اللغة قبل الانتقال عبر الوسيط، بحيث يتم تذكر تفضيلات لغة المستخدم في الزيارات المستقبلية.
ملاحظة حول التحسين التدريجي (Progressive Enhancement): ستعمل الروابط في مبدل اللغة كعناصر
<a>عادية حتى بدون جافا سكريبت. عند توفر جافا سكريبت، ستقوم استدعاءاتsetLocaleبتحديث الكوكيز قبل الانتقال، مما يضمن قيام الوسيط بالتوجيه الصحيح.
الخطوة 7: خريطة الموقع وRobots.txt
توفر Intlayer أدوات لإنشاء خريطة موقع (sitemap) مترجمة وملفات robots.txt ديناميكيًا.
خريطة الموقع (Sitemap)
Intlayer comes with a built-in sitemap generator to help you create a sitemap for your application easily. It handles localized routes and adds the necessary metadata for search engines.
The Intlayer generated sitemap supports thexhtml:linknamespace (Hreflang XML Extensions). Unlike the default sitemap generators that only list raw URLs, Intlayer automatically creates the required bidirectional links between all language versions of a page (e.g.,/about,/about?lang=fr, and/about?lang=es). This ensures search engines correctly index and serve the right language version to the right audience.
أنشئ src/pages/sitemap.xml.ts لإنشاء خريطة موقع تتضمن جميع مساراتك المترجمة.
نسخ الكود إلى الحافظة
import type { APIRoute } from "astro";import { generateSitemap, type SitemapUrlEntry } from "intlayer";const pathList: SitemapUrlEntry[] = [ { path: "/", changefreq: "daily", priority: 1.0 }, { path: "/about", changefreq: "monthly", priority: 0.7 },];const SITE_URL = import.meta.env.SITE ?? "http://localhost:4321";export const GET: APIRoute = async ({ site }) => { const xmlOutput = generateSitemap(pathList, { siteUrl: SITE_URL }); return new Response(xmlOutput, { headers: { "Content-Type": "application/xml" }, });};Robots.txt
أنشئ src/pages/robots.txt.ts للتحكم في زحف محركات البحث.
نسخ الكود إلى الحافظة
import type { APIRoute } from "astro";import { getMultilingualUrls } from "intlayer";const getAllMultilingualUrls = (urls: string[]) => urls.flatMap((url) => Object.values(getMultilingualUrls(url)) as string[]);const disallowedPaths = getAllMultilingualUrls(["/admin", "/private"]);export const GET: APIRoute = ({ site }) => { const robotsTxt = [ "User-agent: *", "Allow: /", ...disallowedPaths.map((path) => `Disallow: ${path}`), "", `Sitemap: ${new URL("/sitemap.xml", site).href}`, ].join("\n"); return new Response(robotsTxt, { headers: { "Content-Type": "text/plain" }, });};تكوين TypeScript
تستخدم Intlayer تقنية توسيع الوحدات (module augmentation) للاستفادة من TypeScript، مما يجعل برمجتك أكثر قوة.


تأكد من أن تكوين TypeScript الخاص بك يتضمن الأنواع المولدة تلقائيًا.
نسخ الكود إلى الحافظة
{ // ... تكوين TypeScript الحالي الخاص بك "include": [ // ... تكوين TypeScript الحالي الخاص بك ".intlayer/**/*.ts", // تضمين الأنواع المولدة تلقائيًا ],}تكوين Git
يوصى بتجاهل الملفات التي تنشئها Intlayer. هذا يتجنب إضافتها إلى مستودع Git الخاص بك.
للقيام بذلك، أضف التعليمات التالية إلى ملف .gitignore الخاص بك:
نسخ الكود إلى الحافظة
# تجاهل الملفات المولدة بواسطة Intlayer.intlayerإضافة VS Code
لتحسين تجربة التطوير الخاصة بك مع Intlayer، يمكنك تثبيت إضافة Intlayer الرسمية لـ VS Code.
التثبيت من VS Code Marketplace
توفر هذه الإضافة:
- إكمال تلقائي لمفاتيح الترجمة.
- اكتشاف الأخطاء في الوقت الفعلي للترجمات المفقودة.
- معاينة مضمنة للمحتوى المترجم.
- إجراءات سريعة لإنشاء وتحديث الترجمات بسهولة.
لمزيد من المعلومات حول استخدام الإضافة، راجع توثيق إضافة VS Code.
(Optional) Step 15: Extract the content of your components
If you have an existing codebase, transforming thousands of files can be time-consuming.
To ease this process, Intlayer propose a compiler / extractor to transform your components and extract the content.
To set it up, you can add a compiler section in your intlayer.config.ts file:
نسخ الكود إلى الحافظة
import { type IntlayerConfig } from "intlayer";
const config: IntlayerConfig = {
// ... Rest of your config
compiler: {
/**
* Indicates if the compiler should be enabled.
*/
enabled: true,
/**
* Defines the output files path
*/
output: ({ fileName, extension }) => `./${fileName}${extension}`,
/**
* Indicates if the components should be saved after being transformed.
*
* - If `true`, the compiler will rewrite the component file in the disk. So the transformation will be permanent, and the compiler will skip the transformation for the next process. That way, the compiler can transform the app, and then it can be removed.
*
* - If `false`, the compiler will inject the `useIntlayer()` function call into the code in the build output only, and keep the base codebase intact. The transformation will be done only in memory.
*/
saveComponents: false,
/**
* Dictionary key prefix
*/
dictionaryKeyPrefix: "",
},
};
export default config;Run the extractor to transform your components and extract the content
نسخ الكود إلى الحافظة
npx intlayer extractتعمق أكثر
إذا كنت تريد معرفة المزيد، يمكنك أيضًا تنفيذ المحرر المرئي أو استخدام نظام إدارة المحتوى (CMS) لإخراج محتواك خارجيًا.