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

next-unprefixed-intl

v3.1.2

Published

unprefixed-intl wrapper for Next.js

Downloads

6

Readme

next-unprefixed-intl

unprefixed-intl wrapper for Next.js

https://petalfan.com => en url

https://petalfan.com => es url

https://petalfan.com => en-GB url

the translations will be read on the server side, in the example of this README using Accept Language Header

Usage

Add an unprefixed-intl.config.json file to the project root:

{
  "messagesPath": "/src/messages",
  "defaultLang": "en",
  "maxAcceptedLanguageSearch": 3,
  "allowLanguageCode": true
}

That will result in the interface (will be used by the package):

interface Config{
    /** Path for the `messages` folder, that will alloc the .json files with the translations, (en-US.json, ...) */
    messagesPath:string,
    /** The default language, that will be used if the preferred language was not found */
    defaultLang:string,
    /** From the list of preferred languages a loop will be run to look for the best match available, this is the
     * limit of iterations this loop can do */
    maxAcceptedLanguageSearch:number
    /** If true: if the complete code is not found, the language code can be used instead, e.g. if the preferred
     * language is `en-US`, but there is no `en-US.json` file but rather a ` en.json`, it will be used */
    allowLanguageCode:boolean
}

Add the translation files inside the messagesPath directory:

en language example: /src/messages/en.json

{
  "Home.component1": {
    "hello_message": "Hello! Welcome!",
    "phrase": "I just got my driver's license, and now I need to get gas for my truck. In the fall, I'll enroll in college, and I'll make sure to check the schedule of my favorite soccer team."
  },
  "Home.component2": {
    "popup.warning_message": "Remember that the default translation file, defined in `defaultLang`, must exist!"
  }
}

es language example: /src/messages/es.json

{
  "Home.component1": {
    "hello_message": "¡Hola! ¡Sea bienvenido!",
    "phrase": "Acabo de obtener mi licencia de conducir y ahora necesito gasolina para mi camión. En el otoño, me inscribiré en la universidad y me aseguraré de consultar el calendario de mi equipo de fútbol favorito."
  },
  "Home.component2": {
    "popup.warning_message": "Recuerde que el archivo de traducción predeterminado, definido en `defaultLang`, ¡debe existir!"
  }
}

en-GB language example: /src/messages/en-GB.json

{
  "Home.component1": {
    "hello_message": "Hello! Welcome!",
    "phrase": "I've just got my driving licence, and now I need to get petrol for my lorry. In the autumn, I'll enrol in university, and I'll make sure to check the timetable of my favourite football team."
  },
  "Home.component2": {
    "popup.warning_message": "Remember that the default translation file, defined in `defaultLang`, must exist!"
  }
}

In the place you want to read the translations:

this example is using Next.js, but it can be in any Node.js project if you use the original package:

/src/app/page.tsx


import { getTranslations } from "next-unprefixed-intl"

export default function Home() {
    /*
    here you will receive the function that returns the 
    translations, based on a path (`"Home.component1"`), 
    and with the accept language header provided by the 
    "next/headers" import
     */
    const t = getTranslations("Home.component1")

    return (
        <p>{t("hello_message")}</p>
    )
}

In addition

You can use generate to generate files based in translations api, in that example, the Google Cloud Translate api

import { generate } from "next-unprefixed-intl"
import { v2 } from "@google-cloud/translate"

const CREDENTIALS = JSON.parse(/*secret, check the Google Cloud Translation api for more info*/)

const translate = new v2.Translate({
    credentials: CREDENTIALS,
    projectId: CREDENTIALS.project_id,
})

async function translateTextFromSource(
    text: string,
    sourceLanguage: string,
    targetLanguage: string,
) {
    const [response] = await translate.translate(text, {
        from: sourceLanguage,
        to: targetLanguage,
    })
    return response
}

const fromLanguage = "en"
generate(
    fromLanguage,
    [
        //["en", "en"], // English
        ["zh", "zh"], // Chinese Mandarin
        ["hi", "hi"], // Hindi
        ["es", "es"], // Spanish
        ["fr", "fr"], // French
        ["ar", "ar"], // Arabic
        ["bn", "bn"], // Bengali
        ["ru", "ru"], // Russian
        ["pt-BR", "pt"], // Portuguese from Brazil
        ["pt-PT", "pt-PT"], // Portuguese from Portugal
        ["pt", "pt"], // Portuguese
        ["id", "id"], // Indonesian
        ["de", "de"], // German
        ["ja", "ja"], // Japanese
        ["ur", "ur"], // Urdu
        ["it", "it"], // Italian
        ["ko", "ko"], // Korean
        ["tr", "tr"], // Turkish
        ["vi", "vi"], // Vietnamese
        ["pl", "pl"], // Polish
        ["jv", "jv"], // Javanese
        ["pa", "pa"], // Punjabi
    ],
    (text, to) => translateTextFromSource(text, fromLanguage, to),
    (to) => {
        console.log(`Successfully generated ${to} translations.`)
        return true
    },
    (error) => {
        console.error("Error during translation:", error)
        return false
    },
)

You can use bestAvailableOption to read the preferred language, in this example the preferred language will be used to change the html language

import { bestAvailableOption } from "next-unprefixed-intl"

...
<html lang={bestAvailableOption()}>
...