Using multiple namespaces in i18next is an effective way to manage and organize translation resources, especially when the application is large or involves multiple functional modules. Namespaces allow you to group translation content into distinct files or modules, making maintenance more streamlined and organized. Here are the steps and examples for using multiple namespaces in i18next:
1. Configure i18next
First, configure multiple namespaces when initializing i18next. This is typically done in your application's entry file or configuration file. Here is an example of how to configure:
javascriptimport i18n from 'i18next'; import Backend from 'i18next-http-backend'; i18n .use(Backend) .init({ lng: 'en', // Default language fallbackLng: 'en', ns: ['common', 'moduleA', 'moduleB'], // Define multiple namespaces defaultNS: 'common', // Default namespace backend: { loadPath: '/locales/{{lng}}/{{ns}}.json' // Resource file path pattern } });
2. Organize Translation Files
Each namespace should have its own translation file. For example, you can organize the files as follows:
shell/locales /en common.json moduleA.json moduleB.json /zh common.json moduleA.json moduleB.json
3. Load Translations with Namespaces
When loading translations, you can specify which namespace to use. If you are using React, you can specify the namespace using the useTranslation hook:
javascriptimport { useTranslation } from 'react-i18next'; function MyComponent() { const { t } = useTranslation('moduleA'); return <h1>{t('key.from.moduleA')}</h1>; }
4. Dynamically Load Namespaces
If your application loads modules on demand, you may also want to load the corresponding translation files on demand. i18next supports dynamic loading of namespaces, which can be achieved using the i18next.loadNamespaces() method:
javascripti18n.loadNamespaces('moduleB', () => { console.log('Namespace moduleB has been loaded'); });
Using multiple namespaces helps you better manage translation resources in large projects, making the internationalization maintenance of each module or component more modular and clear.