npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

gatsby-plugin-i18n-l10n

v5.7.0

Published

Providing i18n and l10n to Gatsby with react-intl. Besides translating pages and labels, you can also translate the slugs and paths and still link between translated sibling pages.

Downloads

537

Readme

gatsby-plugin-i18n-l10n

Codecov GitHub Workflow Status npm npm

Providing i18n and l10n to Gatsby. Besides translating pages and Markdown files, you can also translate the slugs and paths and still link between translated sibling pages. Batteries like a language switcher component are included. The plugin is written in Typescript, has some tests and has only one peer dependency:

  • react-intl: Wrapping the pages with a provider, which makes translation available throughout the app.

Features

  • Generates translated versions of pages.
    • For example, if you have a page src/pages/about.tsx and the languages en-US and de-CH configured, then it will create an en-US and de-CH version of this page. Via the page context of the translated pages, you get to know the locale.
  • Adds fields on MarkdownRemark and Mdx nodes.
  • Puts prefixes into the page paths, but not when it's the default locale.
  • Picks up locale from Markdown file names and provides it via custom fields in GraphQL.
    • It works with gatsby-transformer-remark and gatsby-plugin-mdx.
  • Makes it easy to navigate between the translations of a page.
  • Sets meta tags to provide locale information to crawlers and other machines.
  • Provides useful components like <LocalizedLink> and <LanguageSwitcher>.
  • Helps to translate paths, while keeping the possibility to navigate between the translations of a page.

Usage

  1. Make sure the packages "gatsby": "^5.x" and "react-intl": "^6.x" are dependencies of your Gatsby project.

  2. Install the plugin with npm install gatsby-plugin-i18n-l10n or yarn add gatsby-plugin-i18n-l10n.

  3. Load and configure the plugin from your gatsby-config.js or gatsby-config.ts:

    {
      resolve: `gatsby-plugin-i18n-l10n`,
      options: {
        // string: IETF BCP 47 language tag: default locale, which won't be prefixed
        defaultLocale: `de-CH`,
        // string: absolute site url
        siteUrl: `https://example.com`,
        // locales[]: all locales, which should be available
        locales: [
          {
            // string: IETF BCP 47 language tag of this language
            locale: `en-US`,
            // string: prefix for this language, which will be used to prefix the url, if it's not the default locale
            prefix: `en`,
            // object: mapping of given urls (by filename) to translated urls, if no mapping exists, given url will be used
            slugs: {},
            // object: this messages will be handed over to react-intl and available throughout the website
            messages: {
              "language": "English"
            },
          },
          // another language
          {
            locale: `de-CH`,
            prefix: `de`,
            slugs: {
              '/products/': '/produkte/',
              '/products/#donut-filled-with-jam': '/produkte/#berliner',
              '/services/software-development/': '/dienstleistungen/softwareentwicklung/'
            },
            pageBlacklist: ['/do-not-translate-to-german/'], // If there is a page with the a given path it won't be translated
            messages: {
              "language": "Deutsch"
            },
          },
        ],
        // omit certain path segments (relative directories)
        // be careful not to cause path collisions
        pathBlacklist: [
          '/pages' // /pages/products/gummibears/ becomes /products/gummibears/
        ],
        // set handling of trailing slashes
        // set it to the same value as for the rest of Gatsby
        // behaves like https://www.gatsbyjs.com/docs/reference/config-files/gatsby-config/#trailingslash
        // default: always
        trailingSlash: 'always'
      },
    }

<LanguageSwitcher>

With the built-in <LanguageSwitcher> component users can change between the locales. With resolveLanguageName prop the language names can be provided to the component.

<LanguageSwitcher resolveLanguageName={(locale) => intl.formatMessage({ id: `languages.${locale}` })} />

<LocalizedLink>

<LocalizedLink> wraps Gatsby <Link> component, thus it should be possible to use it in the same way.

<LocalizedLink to="/products/">Produkte</LocalizedLink>

If the configuration from above is used and the user views this link inside the i18n context de-CH the link will lead him to /de/produkte.

<GenericLocalizedLink>

With the built-in <GenericLocalizedLink> component it's possible to use other plugins, which modify Gatsbys <Link> component. Here is an example with Gatsby Plugin Transition Link:

<GenericLocalizedLink to="/imprint/">
  {(args) => (
    <TransitionLink
      to={args.to}
      exit={{
        trigger: ({ exit, node }) => this.interestingExitAnimation(exit, node),
        length: 1,
      }}
      entry={{
        delay: 0.6,
      }}
    >
      Go to page 2
    </TransitionLink>
  )}
</GenericLocalizedLink>

Another example with <AniLink>:

<GenericLocalizedLink to="/imprint">
  {(args) => (
    <AniLink fade to={args.to}>
      Go to Page 4
    </AniLink>
  )}
</GenericLocalizedLink>

createPage()

When you create pages programmatically with createPage() by default the page will only try to set the locale and prefix to the context. With the following options you can instruct the plugin to internationalize the context further:

  • referTranslations: string[]: Refers translations for given locales.
  • adjustPath: boolean: Add locale prefix and replaces slugs.

GraphQL data layer integration

All translation messages are sourced to Gatsbys GraphQL data layer with translation and allTranslation. Here is an example GraphQL query:

export const query = graphql`
  query SomePage($locale: String) {
    pageTitle: translation(locale: { eq: $locale }, key: { eq: "page.some.title" }) {
      message
    }
    pageDescription: translation(locale: { eq: $locale }, key: { eq: "page.some.description" }) {
      message
    }
  }
`;

Development

  1. Clone the project
  2. Open the freshly cloned project with Visual Studio Code and Remote Containers.
  3. Install the projects dependencies with npm install.
  4. Run the tests with npm test.
  5. Install the examples dependencies with npm run example install.
  6. Run the example project with npm run example start.

Alternatives