Gathering detailed insights and metrics for gatsby-plugin-i18next-hmr
Gathering detailed insights and metrics for gatsby-plugin-i18next-hmr
Gathering detailed insights and metrics for gatsby-plugin-i18next-hmr
Gathering detailed insights and metrics for gatsby-plugin-i18next-hmr
Easily translate your Gatsby website into multiple languages w/ HMR support 🔥
npm install gatsby-plugin-i18next-hmr
Typescript
Module System
JavaScript (37.1%)
CSS (32.61%)
TypeScript (30.29%)
Total Downloads
0
Last Day
0
Last Week
0
Last Month
0
Last Year
0
MIT License
1 Stars
6 Commits
1 Watchers
1 Branches
1 Contributors
Updated on May 07, 2021
Latest Version
1.0.0
Package Id
gatsby-plugin-i18next-hmr@1.0.0
Unpacked Size
46.68 kB
Size
12.45 kB
File Count
27
Cumulative downloads
Total Downloads
Last Day
0%
NaN
Compared to previous day
Last Week
0%
NaN
Compared to previous week
Last Month
0%
NaN
Compared to previous month
Last Year
0%
NaN
Compared to previous year
4
4
16
1
Easily translate your Gatsby website into multiple languages.
pages/en/index.js
or pages/es/index.js
.When you build multilingual sites, Google recommends using different URLs for each language version of a page rather than using cookies or browser settings to adjust the content language on the page. (read more)
This plugin does not require fetching translations with graphql query on each page, everything is done automatically. Just use react-i18next
to translate your pages.
yarn add gatsby-plugin-react-i18next i18next react-i18next
or
npm install --save gatsby-plugin-react-i18next i18next react-i18next
1// In your gatsby-config.js 2plugins: [ 3 { 4 resolve: `gatsby-plugin-react-i18next`, 5 options: { 6 path: `${__dirname}/locales`, 7 languages: [`en`, `es`, `de`], 8 defaultLanguage: `en`, 9 10 // you can pass any i18next options 11 // pass following options to allow message content as a key 12 i18nextOptions: { 13 interpolation: { 14 escapeValue: false // not needed for react as it escapes by default 15 }, 16 keySeparator: false, 17 nsSeparator: false 18 }, 19 pages: [ 20 { 21 matchPath: '/:lang?/blog/:uid', 22 getLanguageFromPath: true, 23 excludeLanguages: ['es'] 24 }, 25 { 26 matchPath: '/preview', 27 languages: ['en'] 28 } 29 ] 30 } 31 } 32];
For example,
language resource files | language |
---|---|
/locales/en/translation.json | English |
/locales/es/translation.json | Spanish |
/locales/de/translation.json | German |
You can use different namespaces to organize your translations. Use the following file structure:
|-- language
|-- namespace.json
For example:
|-- en
|-- header.json
|-- footer.json
The default namespace is translation
. Read more about i18next namespaces
Use react i18next useTranslation
react hook and Trans
component to translate your pages.
gatsby-plugin-react-i18next
exposes all react-i18next
methods and components.
Replace Gatsby Link
component with the Link
component exported from gatsby-plugin-react-i18next
1import React from 'react'; 2import {Link, Trans, useTranslation} from 'gatsby-plugin-react-i18next'; 3import Layout from '../components/layout'; 4import Image from '../components/image'; 5import SEO from '../components/seo'; 6 7const IndexPage = () => { 8 const {t} = useTranslation(); 9 return ( 10 <Layout> 11 <SEO title={t('Home')} /> 12 <h1> 13 <Trans>Hi people</Trans> 14 </h1> 15 <p> 16 <Trans>Welcome to your new Gatsby site.</Trans> 17 </p> 18 <p> 19 <Trans>Now go build something great.</Trans> 20 </p> 21 <div style={{maxWidth: `300px`, marginBottom: `1.45rem`}}> 22 <Image /> 23 </div> 24 <Link to="/page-2/"> 25 <Trans>Go to page 2</Trans> 26 </Link> 27 </Layout> 28 ); 29}; 30 31export default IndexPage;
and in locales/en/translations.json
you will have
1{ 2 "Home": "Home", 3 "Hi people": "Hi people", 4 "Welcome to your new Gatsby site.": "Welcome to your new Gatsby site.", 5 "Now go build something great.": "Now go build something great.", 6 "Go to page 2": "Go to page 2" 7}
This example is not using semantic keys instead the entire message will be used as a key. Read more.
gatsby-plugin-react-i18next
exposes useI18next
hook
1import {Link, useI18next} from 'gatsby-plugin-react-i18next'; 2import React from 'react'; 3 4const Header = ({siteTitle}) => { 5 const {languages, changeLanguage} = useI18next(); 6 return ( 7 <header className="main-header"> 8 <h1 style={{margin: 0}}> 9 <Link 10 to="/" 11 style={{ 12 color: `white`, 13 textDecoration: `none` 14 }}> 15 {siteTitle} 16 </Link> 17 </h1> 18 <ul className="languages"> 19 {languages.map((lng) => ( 20 <li key={lng}> 21 <a 22 href="#" 23 onClick={(e) => { 24 e.preventDefault(); 25 changeLanguage(lng); 26 }}> 27 {lng} 28 </a> 29 </li> 30 ))} 31 </ul> 32 </header> 33 ); 34};
Or a more SEO friendly version using Link
component
1import {Link, useI18next} from 'gatsby-plugin-react-i18next'; 2import PropTypes from 'prop-types'; 3import React from 'react'; 4 5const Header = ({siteTitle}) => { 6 const {languages, originalPath} = useI18next(); 7 return ( 8 <header className="main-header"> 9 <h1 style={{margin: 0}}> 10 <Link 11 to="/" 12 style={{ 13 color: `white`, 14 textDecoration: `none` 15 }}> 16 {siteTitle} 17 </Link> 18 </h1> 19 <ul className="languages"> 20 {languages.map((lng) => ( 21 <li key={lng}> 22 <Link to={originalPath} language={lng}> 23 {lng} 24 </Link> 25 </li> 26 ))} 27 </ul> 28 </header> 29 ); 30};
Option | Type | Description |
---|---|---|
path | string | path to the folder with JSON translations |
languages | string[] | supported language keys |
defaultLanguage | string | default language when visiting /page instead of /es/page |
redirect | boolean | if the value is true , / or /page-2 will be redirected to the user's preferred language router. e.g) /es or /es/page-2 . Otherwise, the pages will render defaultLangugage language. Default is true |
siteUrl | string | public site url, is used to generate language specific meta tags |
pages | array | an array of page options used to modify plugin behaviour for specific pages |
i18nextOptions | object | i18next configuration options |
Option | Type | Description |
---|---|---|
matchPath | string | a path pattern like /:lang?/blog/:uid , check path-to-regexp for more info |
getLanguageFromPath | boolean | if set to true the language will be taken from the :lang param in the path instead of automatically generating a new page for each language |
excludeLanguages | array | an array of languages to exclude, if specified the plugin will not automatically generate pages for those languages, this option can be used to replace pages in some languages with custom ones |
languages | array | an array of languages, if specified the plugin will automatically generate pages only for those languages |
Link
Link
component is identical to Gatsby Link component except that you can provide additional language
prop to create a link to a page with different language
1import {Link} from 'gatsby-plugin-react-i18next'; 2 3const SpanishAboutLink = () => ( 4 <Link to="/about" language="es"> 5 About page in Spanish 6 </Link> 7);
Helmet
Helmet
component is identical to gatsby-plugin-react-helmet
component but also provides language related metatags (alternative and canonical links)
Note! To use it you need to have react-helmet
dependency installed. You also need to provide siteUrl
in plugin options for it to work properly.
I18nextContext
Use this react context to access language information about the page
1const context = React.useContext(I18nextContext);
Content of the context object
Attribute | Type | Description |
---|---|---|
language | string | current language |
languages | string[] | supported language keys |
routed | boolean | if false it means that the page is in default language |
defaultLanguage | string | default language provided in plugin options |
originalPath | string | page path in default language |
path | string | page path |
siteUrl | string | public site url provided in plugin options |
The same context will be also available in the Gatsby pageContext.i18n
object
useI18next
This react hook returns I18nextContext
, object and additional helper functions
Function | Description |
---|---|
navigate | This is a wrapper around Gatsby navigate helper function that will navigate to the page in selected language |
changeLanguage | A helper function to change language. The first parameter is a language code. Signature: (language: string, to?: string, options?: NavigateOptions) => Promise<void> . You can pass additional parameters to navigate to different page. |
useI18next
also exposes the output of react i18next useTranslation
so you can use
1const {t} = useI18next();
For example if you have some other plugin or script that generates your blog posts from headless CRM like prismic.io in different languages you would like to exclude those pages, to not generate duplicates for each language key. You can do that by providing pages
option.
1pages: [ 2 { 3 matchPath: '/:lang?/blog/:uid', 4 getLanguageFromPath: true, 5 excludeLanguages: ['es'] 6 } 7];
You have to specify a :lang
url param, so the plugin knows what part of the path should be treated as language key.
In this example the plugin will automatically generate language pages for all languages except es
. Assuming that you have ['en', 'es', 'de']
languages te blog post with the path /blog/hello-world
you will have the following pages generated:
/blog/hello-world
- the English version (if you have en
as a defaultLanguage
)/es/blog/hello-world
- the Spanish version that should exist before you run the plugin (created manually or at build time with a plugin or api call)/de/blog/hello-world
- the German version that is generated automaticallyOmit excludeLanguages
to get all the languages form the path. Make sure that you have pages for all the languages that you specify in the plugin, otherwise you might have broken links.
You can limit the languages used to generate versions of a specific page, for exmaple to limit /preview
page to only English version:
1pages: [ 2 { 3 matchPath: '/preview', 4 languages: ['en'] 5 } 6];
You can use language
variable in gatsby page queries to fetch additional data for each language. For example if you're using gatsby-transformer-json your query might look like:
1export const query = graphql` 2 query($language: String!) { 3 dataJson(language: {eq: $language}) { 4 ...DataFragment 5 } 6 } 7`;
sitemap.xml
for all language specific pagesYou can use gatsby-plugin-sitemap to automatically generate a sitemap during build time. You need to customize query
to fetch only original pages and then serialize
data to build a sitemap. Here is an example:
1// In your gatsby-config.js 2plugins: [ 3 { 4 resolve: 'gatsby-plugin-sitemap', 5 options: { 6 exclude: ['/**/404', '/**/404.html'], 7 query: ` 8 { 9 site { 10 siteMetadata { 11 siteUrl 12 } 13 } 14 allSitePage(filter: {context: {i18n: {routed: {eq: false}}}}) { 15 edges { 16 node { 17 context { 18 i18n { 19 defaultLanguage 20 languages 21 originalPath 22 } 23 } 24 path 25 } 26 } 27 } 28 } 29 `, 30 serialize: ({site, allSitePage}) => { 31 return allSitePage.edges.map((edge) => { 32 const {languages, originalPath, defaultLanguage} = edge.node.context.i18n; 33 const {siteUrl} = site.siteMetadata; 34 const url = siteUrl + originalPath; 35 const links = [ 36 {lang: defaultLanguage, url}, 37 {lang: 'x-default', url} 38 ]; 39 languages.forEach((lang) => { 40 if (lang === defaultLanguage) return; 41 links.push({lang, url: `${siteUrl}/${lang}${originalPath}`}); 42 }); 43 return { 44 url, 45 changefreq: 'daily', 46 priority: originalPath === '/' ? 1.0 : 0.7, 47 links 48 }; 49 }); 50 } 51 } 52 } 53];
You can use babel-plugin-i18next-extract automatically extract translations inside t
function and Trans
component from you pages and save them in JSON.
yarn add @babel/cli @babel/plugin-transform-typescript babel-plugin-i18next-extract -D
babel-extract.config.js
file (don't name it babel.config.js
, or it will be used by gatsby)1module.exports = { 2 presets: ['babel-preset-gatsby'], 3 plugins: [ 4 [ 5 'i18next-extract', 6 { 7 keySeparator: null, 8 nsSeparator: null, 9 keyAsDefaultValue: ['en'], 10 useI18nextDefaultValue: ['en'], 11 discardOldKeys: true, 12 outputPath: 'locales/{{locale}}/{{ns}}.json', 13 customTransComponents: [['gatsby-plugin-react-i18next', 'Trans']] 14 } 15 ] 16 ], 17 overrides: [ 18 { 19 test: [`**/*.ts`, `**/*.tsx`], 20 plugins: [[`@babel/plugin-transform-typescript`, {isTSX: true}]] 21 } 22 ] 23};
package.json
1{ 2 "scripts": { 3 "extract": "yarn run babel --config-file ./babel-extract.config.js -o tmp/chunk.js 'src/**/*.{js,jsx,ts,tsx}' && rm -rf tmp" 4 } 5}
After your messages had been extracted you can use AWS Translate to automatically translate messages to different languages.
This functionality is out of the scope of this plugin, but you can get the idea from this script
This package is based on:
MIT © microapps
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
Found 0/6 approved changesets -- score normalized to 0
Reason
no SAST tool detected
Details
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
159 existing vulnerabilities detected
Details
Score
Last Scanned on 2025-07-07
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More