
วิธีแปลแอป Next.js ด้วย PolyLingo ในเวลาไม่ถึง 30 นาที
By Robert
วิธีแปลแอป Next.js ด้วย PolyLingo ในเวลาไม่ถึง 30 นาที
เมื่อคุณทำตามบทแนะนำนี้เสร็จสิ้น คุณจะมีโปรเจกต์ Next.js App Router ที่รองรับหลายภาษาอย่างสมบูรณ์: สตริงถูกดึงออกมาเป็นไฟล์ messages/en.json ไฟล์ locale ที่แปลแล้วสำหรับทุกภาษาที่คุณต้องการ next-intl จะให้บริการไฟล์ที่ถูกต้องตามเส้นทาง และมีสคริปต์ Node เดียวที่คุณสามารถรันซ้ำได้ทุกครั้งที่เนื้อหาของคุณเปลี่ยนแปลง
ไม่ต้องสมัครแพลตฟอร์มแปลภาษา ไม่มีค่าธรรมเนียมรายภาษาคงที่ การเรียก API ครั้งเดียวจัดการทุกภาษาที่คุณต้องการพร้อมกัน
สิ่งที่คุณต้องมี:
- โปรเจกต์ Next.js ที่ใช้ App Router (Next.js 14 หรือ 15)
- Node.js 18 หรือใหม่กว่า
- บัญชี PolyLingo ฟรีและคีย์ API
ขั้นตอนที่ 1: รับคีย์ API ของ PolyLingo (5 นาที)
สร้างบัญชีฟรีที่ usepolylingo.com แผนฟรีมีโทเค็น 100,000 โทเค็นต่อเดือน ซึ่งเพียงพอสำหรับแปลไฟล์ locale ขนาดกลางเป็นมากกว่า 10 ภาษาได้หลายครั้ง
เมื่อเข้าสู่ระบบแล้ว ไปที่ API keys ในแดชบอร์ดและสร้างคีย์ คุณจะเห็นค่าคีย์เต็มเพียงครั้งเดียว ดังนั้นให้คัดลอกทันที
เพิ่มคีย์นี้เป็นตัวแปรสภาพแวดล้อมในโปรเจกต์ของคุณ อย่าคอมมิตลงในระบบควบคุมเวอร์ชันและอย่าเปิดเผยในโค้ดฝั่งไคลเอนต์:
# .env.local
POLYLINGO_API_KEY="pl_your_key_here"
ตรวจสอบว่า API เข้าถึงได้ก่อนดำเนินการต่อ:
curl -sS "https://api.usepolylingo.com/v1/health"
คุณควรได้รับข้อมูล JSON เล็ก ๆ ที่มีค่า "status": "ok"
ขั้นตอนที่ 2: ติดตั้ง next-intl และตั้งค่า routing (10 นาที)
ติดตั้งไลบรารี:
npm install next-intl
สร้างไฟล์ i18n.ts ที่โฟลเดอร์รากของโปรเจกต์ ไฟล์นี้บอก next-intl ว่าคุณรองรับ locale ไหนบ้างและวิธีโหลดไฟล์ข้อความที่ถูกต้องสำหรับแต่ละคำขอ:
// i18n.ts
import { getRequestConfig } from 'next-intl/server'
export const locales = ['en', 'de', 'fr'] as const
export type Locale = (typeof locales)[number]
export const defaultLocale: Locale = 'en'
export default getRequestConfig(async ({ requestLocale }) => {
let locale = await requestLocale
if (!locale || !locales.includes(locale as Locale)) {
locale = defaultLocale
}
return {
locale,
messages: (await import(`./messages/${locale}.json`)).default,
}
})
เพิ่ม middleware เพื่อเติม prefix เส้นทางด้วย locale:
// middleware.ts
import createMiddleware from 'next-intl/middleware'
import { locales, defaultLocale } from './i18n'
export default createMiddleware({
locales: [...locales],
defaultLocale,
localePrefix: 'as-needed',
})
export const config = {
matcher: ['/((?!api|_next|.*\..*).*)'],
}
ย้ายไฟล์เพจของคุณไปไว้ใต้ app/[locale]/ อัปเดต root layout ให้รับพารามิเตอร์ locale และห่อ children ด้วย NextIntlClientProvider:
// app/[locale]/layout.tsx
import { NextIntlClientProvider } from 'next-intl'
import { getMessages } from 'next-intl/server'
export default async function LocaleLayout({
children,
params,
}: {
children: React.ReactNode
params: Promise<{ locale: string }>
}) {
const { locale } = await params
const messages = await getMessages()
return (
<html lang={locale}>
<body>
<NextIntlClientProvider messages={messages}>
{children}
</NextIntlClientProvider>
</body>
</html>
)
}
ขั้นตอนที่ 3: ดึงสตริงของคุณออกมาเป็นไฟล์ข้อความ JSON (10 นาที)
สร้างโฟลเดอร์ messages/ ที่โฟลเดอร์รากของโปรเจกต์ เพิ่มไฟล์ en.json ที่มีสตริงต้นฉบับของคุณ next-intl ใช้โครงสร้างคีย์แบบซ้อน:
{
"Home": {
"title": "Welcome",
"cta": "Get started"
}
}
อัปเดตเพจของคุณให้ใช้ useTranslations แทนการเขียนสตริงแบบคงที่:
// app/[locale]/page.tsx
import { useTranslations } from 'next-intl'
export default function HomePage() {
const t = useTranslations('Home')
return (
<main>
<h1>{t('title')}</h1>
<button type="button">{t('cta')}</button>
</main>
)
}
ตอนนี้เขียนสคริปต์แปลภาษา สคริปต์นี้จะอ่านไฟล์ messages/en.json ส่งไปยัง PolyLingo API ด้วย format: "json" และเขียนไฟล์ผลลัพธ์หนึ่งไฟล์ต่อ locale เป้าหมาย ธง format: "json" บอก API ให้รักษาโครงสร้างคีย์และแปลเฉพาะค่าข้อความ — คีย์ซ้อน, อาร์เรย์ และชนิดข้อมูลที่ไม่ใช่สตริงจะไม่ถูกเปลี่ยนแปลง
// scripts/translate-messages.mjs
// Run with: node scripts/translate-messages.mjs
import fs from 'node:fs'
import path from 'node:path'
const API_KEY = process.env.POLYLINGO_API_KEY
const API_URL = (process.env.POLYLINGO_API_URL || 'https://api.usepolylingo.com/v1').replace(/\/$/, '')
const TARGETS = ['de', 'fr'] // ขยายอาร์เรย์นี้เพื่อเพิ่ม locale
const enPath = path.join('messages', 'en.json')
const en = JSON.parse(fs.readFileSync(enPath, 'utf8'))
const res = await fetch(`${API_URL}/translate`, {
method: 'POST',
headers: {
Authorization: `Bearer ${API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
content: JSON.stringify(en),
format: 'json',
targets: TARGETS,
model: 'standard',
}),
})
if (!res.ok) {
const err = await res.text()
throw new Error(`PolyLingo ${res.status}: ${err}`)
}
const { translations } = await res.json()
for (const locale of TARGETS) {
const out = path.join('messages', `${locale}.json`)
fs.writeFileSync(out, JSON.stringify(JSON.parse(translations[locale]), null, 2) + '\n')
console.log('Wrote', out)
}
รันสคริปต์:
node scripts/translate-messages.mjs
คุณจะเห็นผลลัพธ์ประมาณนี้:
Wrote messages/de.json
Wrote messages/fr.json
เปิดไฟล์เหล่านั้นและตรวจสอบ คีย์ของคุณจะเหมือนกับใน en.json เท่านั้นค่าข้อความเท่านั้นที่เปลี่ยนแปลง
ขั้นตอนที่ 4: ทดสอบเส้นทางอย่างง่าย (5 นาที)
เริ่มเซิร์ฟเวอร์พัฒนา:
npm run dev
เยี่ยมชม http://localhost:3000 และ http://localhost:3000/de หัวเรื่องและปุ่มควรแสดงผลเป็นภาษาอังกฤษและเยอรมันตามลำดับ เพิ่ม locale เพิ่มเติมโดยการขยายอาร์เรย์ TARGETS ในสคริปต์และอาร์เรย์ locales ใน i18n.ts แล้วรันสคริปต์อีกครั้ง
ตรวจสอบการใช้โทเค็นของคุณในแดชบอร์ด PolyLingo ภายใต้ Usage สำหรับไฟล์ locale ขนาดเล็กที่แปลเป็นสองภาษา คุณจะใช้โทเค็นเพียงไม่กี่ร้อยจากโควต้ารายเดือนของคุณ
ต่อไปนี้ควรทำอย่างไร
เพิ่ม locale เพิ่มเติม. สคริปต์ส่งคำขอเพียงครั้งเดียวไม่ว่าจะมีรายการใน TARGETS กี่รายการ การเพิ่มภาษาญี่ปุ่น, สเปน และอาหรับ จะเสียค่าใช้จ่ายเพียงหนึ่งครั้งเรียก API ไม่ใช่สามครั้ง
เชื่อมต่อกับ CI. เพิ่ม POLYLINGO_API_KEY เป็นความลับของรีโพซิทอรีใน GitHub Actions และรันสคริปต์เป็นส่วนหนึ่งของ pipeline การสร้างไฟล์ locale ของคุณจะซิงค์โดยอัตโนมัติทุกครั้งที่ en.json เปลี่ยนแปลง
แปลรูปแบบอื่น ๆ. รูปแบบสคริปต์เดียวกันนี้ใช้ได้กับหน้าเอกสาร Markdown (format: "markdown") และเทมเพลตอีเมล HTML (format: "html") API จะรักษาโครงสร้างในทุกกรณี
ใช้ endpoint แบบ batch สำหรับโปรเจกต์ขนาดใหญ่. หากคุณมีไฟล์ JSON หลายไฟล์แยกกัน (เช่น ไฟล์ละฟีเจอร์) POST /translate/batch รองรับสูงสุด 100 รายการในคำขอเดียว แต่ละรายการมี id และ format ของตัวเอง
ทดลองใช้ฟรี
แผนฟรีของ PolyLingo มีโทเค็น 100,000 โทเค็นต่อเดือน ไม่ต้องใช้บัตรเครดิต
curl -sS -X POST "https://api.usepolylingo.com/v1/translate" \
-H "Authorization: Bearer $POLYLINGO_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"content": "{\"Home\":{\"title\":\"Welcome\",\"cta\":\"Get started\"}}",
"format": "json",
"targets": ["de", "fr", "es", "ja"]
}'