一个适用于 Next.js 的最小依赖的翻译系统

Page of a dictionary

15 Nov 2023|6 min read

2023年11月15日|阅读时间:6分钟

Source code & Live demo

源代码 & 在线演示

Introduction

介绍

I’ve been doing some web speed performance checks on the Next.js websites we are building at my current company lately, and one of the things that I noticed is that the translation system we are using is adding a lot of weight to the bundle size. I decided to create a minimal translation system that doesn’t add any dependencies to the bundle size. Of course this is no shade to the existing translation systems out there, but I wanted to see if I could create something that is minimal and dependency-free, without all the functionality which systems like next-intl provide.

最近,我在我目前的公司对我们构建的Next.js网站进行了一些网页速度性能检查,其中一件我注意到的事情是我们使用的翻译系统增加了很多包大小。我决定创建一个最小的翻译系统,不会增加任何依赖项的包大小。当然,这并不是对现有翻译系统的贬低,但我想看看是否能够创建一个最小和无依赖的系统,而不需要像next-intl这样的系统提供的所有功能。

Setting up the backend

设置后端

For the purpose of this blog and demo I decided to use POEditor to host my translations. They have a generous free tier which is more than enough for this demo. I created a project, added 2 languages (NL and EN) and added a few translations to it.

为了这篇博客和演示,我决定使用POEditor来托管我的翻译。他们有一个慷慨的免费套餐,对于这个演示来说已经足够了。我创建了一个项目,添加了2种语言(NL和EN),并添加了一些翻译。

Screenshot of POEditor

Setting up the frontend

设置前端

Getting started with a new Next.js app is easy, just run npx create-next-app, follow the steps in your terminal and you’re good to go. For this demo and blog I’m using the Pages Router, I might do another blog post on doing the same in the App Router later, but this might work a bit differently since React Context can not be used in RSC. In next.config.js I added

开始一个新的Next.js应用很容易,只需运行npx create-next-app,按照终端中的步骤进行操作,然后就可以开始了。对于这个演示和博客,我使用了Pages Router,以后可能会写另一篇博客来介绍在App Router中进行相同操作的方法,但这可能会有些不同,因为React Context不能在RSC中使用。在next.config.js中,我添加了

i18n: {
 defaultLocale: 'en',
 locales: ['en', 'nl'],
},

to add an extra language (Dutch) to the project.

添加一个额外的语言(荷兰语)到项目中。

Setting up the translation fetching from POEditor

设置从POEditor获取翻译

Using the Fetch API, I’m fetching the translations for my project from P...

开通本站会员,查看完整译文。

首页 - Wiki
Copyright © 2011-2024 iteam. Current version is 2.125.0. UTC+08:00, 2024-05-03 15:11
浙ICP备14020137号-1 $访客地图$