Search engine optimization (SEO) is a great way to organically reach more people and conquer new markets. Nuxt is a popular JavaScript framework that can significantly help your applications rank better on Google. This tutorial will walk you through the internationalization process of Nuxt.js from start to finish.

Search engine optimization (SEO) is a core element of a strong global growth strategy. In order to be able to run your application globally, you need to remove this barrier from the start.

Nuxt is a popular JavaScript framework that can significantly help your applications achieve better Google rankings using SEO. It is based on vue.js and supports both single-page application (SPA) and server-side rendering (SSR) formats.

With its support for pre-rendering and vue-meta out of the box, it has become the framework of choice for all applications that need better SEO but still use the great vue.js syntax and libraries.

In this end-to-end Nuxt.js tutorial, we will show you how to internationalize your Nuxt.js application and make it suitable for the global market. Set off!

Get started with our nuxt.js tutorial

For this tutorial, we need the following libraries:

  1. Create-nuxt-app — Build our NUxT application

  2. Nuxt-i18n — Localize our application

Nuxt provides a simple way to set up the basic structure with various options through the create-Nuxt-app utility. Without having to install the utility first, we can use and use it NPX directly.

Let’s create a nuxt.js application using the following command:

npx create-nuxt-app nuxt-intl
Copy the code

You can add any entry you choose _ for _ project name, _ project description, and _ author name. _ We can choose BETWEEN NPM and YARN. Simply choose the one you feel most comfortable with. It’s a good practice to always use ESLint to detect syntax errors. Prettier I prefer Prettier because it makes my code look well-formed and forces multiple developers working on the same code to use a certain format so the code remains uniform.

My setup is as follows: After installation, navigate to the project directory and run the application:

cd nuxt-intl 
npm run dev
Copy the code

Open http://localhost:3000/ in your browser and you will see the default application page.

Localization basics

In this tutorial, we will use a library called NuxT-i18n, based on VUE-i18n, and some nuxT-specific localization options. Before installing the NuxT-I18N package, let’s take a look at the basics of localization and the various options available in the library.

We define key-value pairs for each language, where the keys for all languages remain the same, and the values are translations for that language.

// English
{
  "hello": "Hello"
}
// French
{
  "hello": "Bonjour"
}
Copy the code

We have two translation options.

  1. Vue components inside
  2. External JSON or Js file.

Translation within Vue components

You can also choose to add translations directly from the.vue file. These translations are primarily used in component-specific locales, which is perfectly fine for smaller applications. However, as your application grows over time, it becomes very difficult to maintain. An increase in component size results in repeated translations everywhere. Just as importantly, you’ll likely have translators responsible for string translation — they probably don’t know the Vue component — it’s not ideal to do translation inside the Vue component.

<i18n> { "en": { "hello": "hello!" }, "fr": {"hello": "Bonjour!" } } </i18n> <template> </template>Copy the code

External JSON or JS file

We can set up separate files for each language. It’s more like a key-value file. Each language has the same key corresponding to a particular translation. This is the most commonly recommended method and is easy to maintain. This not only prevents duplication, as we can refer to previous translations, but also allows us to group JSON appropriately based on functionality and so on.

//en.json 
{   
  "message": "Hello", 
  "login": {
    "username": "User Name",
    "password": "Password"
  }
}
Copy the code

The installation package

Let’s install nuxT-I18N and configure it.

npm i nuxt-i18n
Copy the code

Since Nuxt does not have a CLI to automatically generate a vue-I18n configuration like vue-CLI for, we had to add the following configuration to set up the plug-in.

Let’s create a folder and our configuration i18n.js in the config file.

import en from '.. /locales/en.json' import fr from '.. /locales/fr.json' export default { locale: 'en', fallbackLocale: 'en', messages: { en, fr } }Copy the code

In this configuration, we use external files to store our translated text. For example, let’s use English and French. We can all pass the default and backup locale to the plug-in. In the next step, we create these two external files to store our translations.

Locales creates a directory in the root folder and two files, en.json and fr.json, which will contain all of our translations.

locales/en.json
{
 "message": "Hello!"
}
locales/fr.json

{
 "message": "Bonjour"
}
Copy the code

Finally, let’s add this library to our nuxt.config.js file so nuxT knows about it. Now we can use it in our application.

nuxt.config.js import i18n from './config/i18n' buildModules: [ /* other modules */ [ 'nuxt-i18n', { vueI18nLoader: True, defaultLocale: 'fr', locales: [{code: 'en', name: 'English'}, {code: 'fr', name: 'Francais'}], vueI18n: i18n } ] ]Copy the code

The vueI18nLoader is optional. This will enable us to write translations in Vue components. Let’s check that the package works: Open pages/index.vue and update the title as follows:

pages/index.vue <template> <div class="container"> <h1 class="title">{{ $t('message') }}</h1> <! -- some code --> </div> </template>Copy the code

Here, $t() tells our Nuxt application to use key based on the translated version of the chosen language. Run the application again and you can see our English message on the screen!

Let’s manually update defaultLocale in our file: nuxt.config.jsfr

nuxt.config.js [ 'nuxt-i18n', { defaultLocale: 'fr', locales: [ { code: 'en', name: 'English' }, { code: 'fr', name: 'Francais'}], vueI18n: i18n}]Copy the code

We’re almost done with our setup. Because we update the code manually, each change to the locale becomes tedious. Let’s create a drop-down menu to select the language.

Components/LanguageInput vue, use the following code creates a component:

components/LanguageInput.vue
<template>
  <div class="lang-dropdown">
    <select v-model="$i18n.locale">
      <option
        v-for="lang in $i18n.locales"
        :key="lang.code"
        :value="lang.code"
        >{{ lang.name }}</option
      >
    </select>
  </div>
</template>
<script>
export default {}
</script>
Copy the code

Let’s add this component to our file. Now we can switch between languages with ease. That’s great! Let’s delve into the different approaches to localization techniques offered by libraries and look at examples of each. pages/Index.html

Naming format

In some cases, not every word needs to be translated, such as proper nouns (first or last name, place names), URLS, etc. To avoid copying them in every locale file, we can apply name formatting techniques.

locales/en.json
{
  "copyrightMessage": "Copyright: All Rights Reserved { name }"
}
Copy the code

We can use it in our component as follows:

 <p>{{ $t('copyrightMessage', { name: 'Phrase.com' }) }}</p>
Copy the code

If we have multiple text fragments that do not need to be translated, we can also use the list method.

 locales/en.json
{
  "welcomeMessage": "Welcome! {0}, Your Email: {1} has been verified successfully"
}

<p>{{ $t('copyrightMessage', ['Preetish HS', '[email protected]']) }}</p>
Copy the code

Since each language has its own specific structure, this technique gives the translator the flexibility to place any value anywhere in the sentence.

diversified

Without actual data, it is often difficult to predict numbers. For example, when you can’t predict the number of items, you’ll see text fragments, such as Style (s) or category(s). This more or less works, but we can take advantage of the library’s capabilities and apply the appropriate plural form. To do this, we can pass the quantity value and the package will send the corresponding translation.

locales/en.json
{
  "style": "Style | Styles"
}
Copy the code

We need to use $tc() (Translation Count) instead of plain$t() :

<p>{{ $tc('style', 1) }}</p>
<p>{{ $tc('style', 2) }}</p>
// output 
Style
Styles
Copy the code

Our countable translator looks much better now!

If you need to perform more complex counts, the library can also help you (see it in action in the examples below). We can also customize plural rules for languages that have different plural rules.

locales/en.json
{
  "apple": "no apples | one apple | {count} apples",
  "banana": "no bananas | {n} banana | {n} bananas"
}
<p>{{ $tc('apple', 10, { count: 10 }) }}</p>
<p>{{ $tc('apple', 10) }}</p>
<p>{{ $tc('apple') }}</p>
<p>{{ $tc('apple', 0) }}</p>
 
<p>{{ $tc('banana') }}</p>
<p>{{ $tc('banana', 0) }}</p>
<p>{{ $tc('banana', 1, { n: 1 }) }}</p>
<p>{{ $tc('banana', 1) }}</p>
<p>{{ $tc('banana', 100, { n: 'too many' }) }}</p>
//output
10 apples
10 apples
one apple
no apples
 
1 banana
no bananas
1 banana
1 banana
too many bananas
Copy the code

Number localization

Different languages and regions represent numbers (monetary amounts, dates, times, etc.) in different ways. Some use comma-separated numbers, others use space-separated numbers. Currency symbols can also have prefixes or suffixes. Therefore, displaying numbers correctly is essential if you want to have a perfect user experience, acquire and retain users.

To implement digital formats, let’s create a new directory called formats and add a file numberFormats.js. This is where we can define all our number formats.

formats/numberFormats.js
export const numberFormats = {
  en: {
    currency: {
      style: 'currency',
      currency: 'USD'
    }
  },
  'en-IN': {
    currency: {
      style: 'currency',
      currency: 'INR'
    }
  },
  fr: {
    currency: {
      style: 'currency',
      currency: 'EUR'
    }
  }
}
Copy the code

In this case, based on Intl.NumberFormat, the library automatically gets the currency format and symbols for us. Now we need to let our library know that we need to use these formats. Let’s add this file to our setup methods.

config/i18n.js import { numberFormats } from '.. /formats/numberFormats' import en from '.. /locales/en.json' import fr from '.. /locales/fr.json' export default { defaultLocale: 'en', fallbackLocale: 'en', numberFormats, messages: { en, fr } }Copy the code

We can now use these in our components. The $n() format we use here lets the library know that we are trying to access the numeric format. We can explicitly pass the locale to the method, as shown below. If we don’t pass, it will adopt the currently selected language. The number format for the language must be defined in the numberFormats. Js file for it to work.

< p > {{ $n(1000000, 'currency') }} </ p > 
< p > {{ $n(7000000, 'currency', 'en-IN') }} </ p > 
< p > {{ $n(7000000, 'currency', 'fr') }} </ p >
Copy the code

Money looks much better with symbols and correct formatting, the international numeric system for the US dollar (USD) and the Indian numeric system for the Rupee (INR).

Date and time localization

Similar to digital localization, date and time formats vary by language and region. We followed the same process and created another file, dateTimeFormats. Js, to define date and time formats in different languages.

Different parts of the application use multiple date formats. We can give these use cases specific names, such as Short, Long,reportDateFormat

Such as:

  1. Last login time format:Sat, 20 Jun, 2020, 9:55 pm
  2. Transaction Date format:Jun 27, 2020

The following table shows the attributes we can have in the date-time input. The corresponding value shows how the property is displayed.

locales/dateTimeFormats.js
export const dateTimeFormats = {
  en: {
    short1: {
      year: 'numeric',
      month: 'short',
      day: 'numeric'
    },
    long: {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
      weekday: 'short',
      hour: 'numeric',
      minute: 'numeric'
    }
  },
  'en-IN': {
    short1: {
      year: 'numeric',
      month: 'short',
      day: 'numeric'
    },
    long: {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
      weekday: 'short',
      hour: 'numeric',
      minute: 'numeric',
      hour12: true
    }
  }
}
Copy the code

To use these formats in our application, we use the $d() symbol. As with numeric formats, if we do not explicitly pass locale, the currently selected locale will be used. If the latter does not define the format, the backup language format is used. Therefore, make sure you define the format for the supported locale.

<p>{{ $d(new Date(), 'short') }}</p>
<p>{{ $d(new Date(), 'long', 'en-IN') }}</p>

//output
Jun 12, 2020
Mon, 12 Jun, 2020, 11:45 am
Copy the code

Just like our digital formats, the library will automatically format dates and times according to international standards.

Nuxt specific localization

Nuxt-i18n The advantage of using VUE-I18n over regular use is that it provides additional options for the localization route, as well as many SEO-related benefits.

Localization route

Just by looking at our URL, we won’t know which language the application is currently using. We rely on local storage or cookies to hold our locale preferences.

To better understand this, we need to create two more pages, about. vue and then contact. vue to add links to these pages to our index.vue page.

<template>
  <div>
    <nuxt-link to="/about">{{ $t('about') }}</nuxt-link>
    <nuxt-link to="/contact">{{ $t('contact') }}</nuxt-link>
  </div>
</template>
Copy the code

Now, if we navigate to the About page, it opens localhost:3000/about regardless of the language choice. It would have been much better to add locale prefixes to our URL (localhost:3000/fr/about). To achieve this, there are two strategies:

  • No default prefix: our default language,enWill not be prefixed, while other languages, such as French, will have urls about the page:localhost:3000/fr/
  • Prefixes: With this policy, all languages, including our default language, will have prefixes.
  • Prefix and Default: This policy combines the first two. That is, the default language will have both prefixed and unprefixed versions.

By default, NUxT-I18n has already created a prefix route for us. Without any extra code, it will apply the third strategy.

//routes generated
[
 {
    path: "/",
    component: _3237362a,
    name: "index___en"
  },
  {
    path: "/fr/",
    component: _3237362a,
    name: "index___fr"
  },
  {
    path: "/about",
    component: _71a6ebb4,
    name: "about___en"
  },
  {
    path: "/fr/about",
    component: _71a6ebb4,
    name: "about___fr"
  },
 {
    path: "/contact",
    component: _71a6ebb4,
    name: "about___en"
  },
  {
    path: "/fr/contact",
    component: _71a6ebb4,
    name: "about___fr"
  }
]
Copy the code

If we navigate to localhost:3000/fr/about, it will automatically load the French translation on our About page. However, if we browse through

. To do this, we pass a function called localePath() with the associated page name. LocalePath (), provided by the nuxT-i18n library, returns the route passed in.

< nuxt-link :to= "localePath('about')" >{{ $ t ( 'about' ) }}< /nuxt-link > < nuxt-link :to= "localePath('contact')" >{{  $ t ( 'contact' ) }}< /nuxt-link >Copy the code

The default translation will work as is when you change the translation to French and then click about it will now open localhost:3000/fr/about. The about page

If the default language is selected, the routing path remains the same. Clicking about opens to localhost:3000/about. If you now change the translation to French, and then click About, it will open as localhost:3000/fr/about.

To use the prefix “lang” for our default language, we need to pass a Strategy attribute to our Nuxt configuration.

nuxt.config.js
// nuxt.config.js
['nuxt-i18n', {
  strategy: 'prefix'
}]
Copy the code

Now load localhost:3000 and it will automatically redirect to localhost:3000/en. To remove the default language prefix URL, set the policy to prefix_EXCEPt_default. This invalidates the URL, such as localhost:3000/en.

Search Engine Optimization (SEO)

If this SEO attribute is set to true during initialization, the library performs various SEO improvements. We also need to pass in the ISO for each locale that the library uses to perform these optimizations:

  1. updatelangAttributes in HTML tags
  2. hreflangGeneration of anchor tags<a href="" hreflang="<selected-locale-iso>">
  3. Open the Graphical Locale TAB, for exampleog:localeog:locale:alternate

Let’s update our plug-in initialization to automatically do these optimizations for us. This will wrap up our nuxt.js tutorial.

nuxt.config.js [ 'nuxt-i18n', { strategy: 'prefix', defaultLocale: 'en', seo: true, locales: [ { code: 'en', name: 'English', iso: 'en - US'}, {code: 'fr, name:' Francais, iso: 'fr - fr'}], vueI18n: i18n}]Copy the code

Conclusion Internationalizing NUxT-I18N will make your NUxT applications accessible anywhere in the world. I sincerely hope that this nuxt.js tutorial helps you get started right. For more techniques for localizing Vue/Nuxt applications, visit the official VUE-I18N documentation and the NuxT-I18N documentation. If you’re confident and want to start internationalizing, make sure you try Phrase for free. With its powerful API and powerful toolkit, it will automate your I18N and L10N processes from the start!

Source link: zhuanlan.zhihu.com/p/402294002