Giter Club home page Giter Club logo

gatsby-plugin-intl's Introduction

gatsby-plugin-react-intl

If can, try theme gatsby-theme-i18n, this plugin will no longer be actively maintained

gatsby-plugin-react-intl has supported gatsby v3! Please upgrade gatsby-plugin-react-intl to ^3.0.0 to use it

For gatsby v2, please use [email protected]

Internationalize your Gatsby site.

Fork from https://github.com/wiziple/gatsby-plugin-intl

Here are added features:

  • ignoredPaths: paths that you don't want to genereate locale pages, example: ["/dashboard/","/test/**"], string format is from micromatch https://github.com/micromatch/micromatch
  • redirectDefaultLanguageToRoot: option for use / as defaultLangauge root path. if your defaultLanguage is ko, when redirectDefaultLanguageToRoot is true, then it will not generate /ko/xxx pages, instead of /xxx
  • fallbackLanguage: option to fallback to the defined language instead of the defaultLanguage if the user langauge is not in the list

The other feature just like https://github.com/wiziple/gatsby-plugin-intl

Features

  • Turn your gatsby site into an internationalization-framework out of the box powered by react-intl.

  • Support automatic redirection based on the user's preferred language in browser provided by browser-lang.

  • Support multi-language url routes in a single page component. This means you don't have to create separate pages such as pages/en/index.js or pages/ko/index.js.

  • Support ignore paths that you don't need to generate locale pages.

Why?

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)

Starters

Demo: http://gatsby-starter-default-intl.netlify.com

Source: https://github.com/wiziple/gatsby-plugin-intl/tree/master/examples/gatsby-starter-default-intl

Showcase

Feel free to send us PR to add your project.

How to use

Install package

npm install --save gatsby-plugin-react-intl

Add a plugin to your gatsby-config.js

// In your gatsby-config.js
plugins: [
  {
    resolve: `gatsby-plugin-react-intl`,
    options: {
      // language JSON resource path
      path: `${__dirname}/src/intl`,
      // supported language
      languages: [`en`, `ko`, `de`],
      // language file path
      defaultLanguage: `ko`,
      // option to redirect to `/ko` when connecting `/`
      redirect: true,
      // option for use / as defaultLangauge root path. if your defaultLanguage is `ko`, when `redirectDefaultLanguageToRoot` is true, then it will not generate `/ko/xxx` pages, instead of `/xxx`
      redirectDefaultLanguageToRoot: false,
      // paths that you don't want to genereate locale pages, example: ["/dashboard/","/test/**"], string format is from micromatch https://github.com/micromatch/micromatch
      ignoredPaths: [],
      // option to fallback to the defined language instead of the `defaultLanguage` if the user langauge is not in the list
      fallbackLanguage: `en`,
    },
  },
]

You'll also need to add language JSON resources to the project.

For example,

language resource file language
src/intl/en.json English
src/intl/ko.json Korean
src/intl/de.json German

Change your components

You can use injectIntl HOC on any react components including page components.

import React from "react"
import { injectIntl, Link, FormattedMessage } from "gatsby-plugin-react-intl"

const IndexPage = ({ intl }) => {
  return (
    <Layout>
      <SEO title={intl.formatMessage({ id: "title" })} />
      <Link to="/page-2/">
        {intl.formatMessage({ id: "go_page2" })}
        {/* OR <FormattedMessage id="go_page2" /> */}
      </Link>
    </Layout>
  )
}
export default injectIntl(IndexPage)

Or you can use the new useIntl hook.

import React from "react"
import { useIntl, Link, FormattedMessage } from "gatsby-plugin-react-intl"

const IndexPage = () => {
  const intl = useIntl()
  return (
    <Layout>
      <SEO title={intl.formatMessage({ id: "title" })} />
      <Link to="/page-2/">
        {intl.formatMessage({ id: "go_page2" })}
        {/* OR <FormattedMessage id="go_page2" /> */}
      </Link>
    </Layout>
  )
}
export default IndexPage

How It Works

Let's say you have two pages (index.js and page-2.js) in your pages directory. The plugin will create static pages for every language.

file English Korean German Default*
src/pages/index.js /en /ko /de /
src/pages/page-2.js /en/page-2 /ko/page-2 /de/page-2 /page-2

Default Pages and Redirection

If redirect option is true, / or /page-2 will be redirected to the user's preferred language router. e.g) /ko or /ko/page-2. Otherwise, the pages will render defaultLangugage language. You can also specify additional component to be rendered on redirection page by adding redirectComponent option.

Plugin Options

Option Type Description
path string language JSON resource path
languages string[] supported language keys
defaultLanguage string default language when visiting /page instead of ko/page
redirect boolean if the value is true, / or /page-2 will be redirected to the user's preferred language router. e.g) /ko or /ko/page-2. Otherwise, the pages will render defaultLangugage language.
redirectComponent string (optional) additional component file path to be rendered on with a redirection component for SEO.

Components

To make it easy to handle i18n with multi-language url routes, the plugin provides several components.

To use it, simply import it from gatsby-plugin-react-intl.

Component Type Description
Link component This is a wrapper around @gatsby’s Link component that adds useful enhancements for multi-language routes. All props are passed through to @gatsby’s Link component.
navigate function This is a wrapper around @gatsby’s navigate function that adds useful enhancements for multi-language routes. All options are passed through to @gatsby’s navigate function.
changeLocale function A function that replaces your locale. changeLocale(locale, to = null)
IntlContextConsumer component A context component to get plugin configuration on the component level.
injectIntl component https://github.com/yahoo/react-intl/wiki/API#injection-api
FormattedMessage component https://github.com/yahoo/react-intl/wiki/Components#string-formatting-components
and more... https://github.com/yahoo/react-intl/wiki/Components

License

MIT © Daewoong Moon

gatsby-plugin-intl's People

Contributors

0xshynn avatar angrypie avatar cddlee avatar chrsep avatar dependabot[bot] avatar dianakhuang avatar fabianrios avatar fujikky avatar gandreadis avatar hoangbaovu avatar jdahdah avatar jhoffmcd avatar lejard-h avatar olegshilov avatar onestopjs avatar sir-will avatar talensjr avatar themattcode avatar theowenyoung avatar violy avatar wiziple avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

gatsby-plugin-intl's Issues

[Question] How could I pass the locale to the graphql query param

Hi, I want to pass the locale to the query like below since I fetch data from contentful. How could I do it?

query Query($slug: String!, $language: String) {
  page: contentfulPage(slug: {eq: $slug}, node_locale: {eq: $language}) {
    ...pageMetaFields
    content {
   ...
    }
    node_locale
  }
}

I check the context and see that we already have the language there.

 {
  language: 'en-US',
  intl: {
    language: 'en-US',
    languages: [ 'en-US', 'ja' ],
    messages: { title: 'Gatsby English' },
    routed: false,
    originalPath: '/exp-postgresql/',
    redirect: false,
    redirectDefaultLanguageToRoot: true,
    defaultLanguage: 'en-US',
    ignoredPaths: []
  },
  slug: 'some-slug'
}

I try to pass the language but my query doesn't pick it up

export function onCreatePage({ page, actions }: CreatePageArgs) {
  const { createPage, deletePage } = actions;
  const slug = page.path.replace(/\//g, '') || '/';
  deletePage(page);

  createPage({ ...page, context: { 
    ...page.context, slug
   } });
}

Feature Request: Detect language from URL

Hello, i'm experimenting with your plugin and i have a request, if possible.

Is there a way to get the current locale in the URL?
For example:
I'm visiting the webite from Italy, so this

const intl = useIntl()
const lang = intl.locale

results in lang to be equal to it.

If i then navigate to /en/index, the lang variable remains equal to it.

What will be useful to me is a different variable (urlLocale ?) telling me the locale as per the URL, even if it is different from the user browser locale.

This way i can show english pages if the user "switches" language from the URL.

iOS 13 : Error: Cannot find react-intl/locale-data/fr

Hi,
I am having an issue on iOS13 which prevents the page from loading fully.
I tried on both mobile Safari and mobile Firefox, same result from the console :

Error: Cannot find react-intl/locale-data/fr

It looks like a polyfill issue with format.js
I switched to gatsby-plugin-intl (version ^0.3.3) and I am not getting the error anymore.

Feature request: skip root pages

Since the original project seems to have been abandoned, and this one has enabled me to upgrade my projects to Gatsby v3 (thanks @theowenyoung!), I thought I would post this feature request here for discussion.

I would like to be able to skip generating root pages that have been replaced by the localized versions. This should be compatible with pages that are generated via gatsby-node.js (e.g., from a CMS) as well as file-based ones. At the same time, this feature would need to preserve root paths for pages that should not be localized, by respecting the new ignoredPaths setting. An example that comes up often in my work is a /blog/, which is rarely translated.

So in other words:

/about/
/en/about/
/de/about/
/services/
/en/services/
/de/services/
/blog/
/en/blog/
/de/blog/
etc…

Right now, generating these unwanted pages means ~33% of page queries are unnecessary (for a bilingual website), and build times are higher than they need to be (including superfluous image transformations, depending on the project setup). It also means that we need to be extra careful about duplicate content by excluding these pages from /sitemap.xml (which entails a lot of customization of the settings for plugins like gatsby-plugin-sitemap) – apart from the standard stuff like generating canonical meta tags.

What do you think? Is this something that is easily developed, or am I missing some caveats?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.