Giter Site home page Giter Site logo

nuxt-modules / i18n Goto Github PK

View Code? Open in Web Editor NEW
1.6K 1.6K 461.0 20.24 MB

I18n module for Nuxt

Home Page: https://i18n.nuxtjs.org

License: MIT License

JavaScript 0.33% TypeScript 97.04% Vue 2.37% Shell 0.25%
i18n javascript nuxt nuxt-module routing vue

i18n's People

Contributors

adriaandotcom avatar atinux avatar bobbiegoede avatar borghol avatar danielroe avatar dargmuesli avatar exer7um avatar gabortorma avatar hoersamu avatar ineshbose avatar kazupon avatar marcopns avatar mickl avatar mikield avatar mosaab-emam avatar mothership-nik-wolf avatar mroddev avatar muhammadm1998 avatar niklaswolf avatar pablolion avatar rchl avatar renovate[bot] avatar stefanotesla avatar szwenni avatar takcastel avatar tituskirch avatar tomkremer avatar userquin avatar wxh06 avatar yassilah avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

i18n's Issues

How to store Translations in Files? and force UTF-8 loading?

Hello,
thank you for this awesome plugin :)

i have some Questions:

  1. How to store Translations in Files, like locales/en.json and loacales/fr.json?

both of Messages and Routes! in separate files.

module.exports = {
  modules: [
    ['nuxt-i18n', {
      locales: [
        {
          code: 'en',
          iso: 'en-US',
          name: 'English'
        },
        {
          code: 'fr',
          iso: 'fr-FR',
          name: 'Français'
        }
      ],
      defaultLocale: 'en',
      vueI18n: {
        messages: {
          fr: {
            home: 'Accueil',
            about: 'À propos',
            category: 'Catégorie'
          },
          en: {
            home: 'Homepage',
            about: 'About us',
            category: 'Category'
          }
        },
        fallbackLocale: 'en'
      },
      routes: {
        about: {
          fr: '/a-propos',
          en: '/about-us'
        },
        category: {
          fr: '/categorie'
        },
        'category-slug': {
          fr: '/categorie/:slug'
        }
      }
    }]
  ]
}

  1. i have published an issues in vue-i18n repo,
    kazupon/vue-i18n#274
    this problem appears when naming route to another language different from Latin!

the links works fine navigation, as expected.

but the real problem when try to refresh the page and the route is like this:
http://localhost:3000/cn/周有七天 or http://localhost:3000/ar/الرئيسية

the page won't load and redirect me to error 404.
try to use your plugin with this repo https://github.com/vuetifyjs/nuxt.
thank you again.

This question is available on Nuxt.js community (#c2)

Nested fixed routes example

Hey again!

I'm currently having the following route construct:

pages/
├── work/
│   ├── index.vue
│   ├── foobar.vue
│   ├── bazfoo.vue

Now I want to translate the work route but leave the child routes "as they are".

/work -> /newname (linking to /work/index.vue)
/work/foobar -> /newname/foobar
/work/bazfoo -> /newname/bazfoo

Is this achievable? If so, do I need to add each route manually? 🤔

This question is available on Nuxt.js community (#c21)

[Bug Report] Custom Routes Doesn't Work

Versions and Environment

Nuxt I18n: 2.7.1
Nuxt: 1.4.0
Vue: 2.5.13
Browsers: Chrome 65.0.3325.162
OS: Linux x86_64

Steps to reproduce

  1. Clone the repository on the link below, run npm run dev or npm run generate.
  2. Open /hello and /halo.

Expected Behavior

/id/halo display the indonesia-translated version of /hello

Actual Behavior

/id/halo display error not found page.

Reproduction Link

https://github.com/jefrydco/nuxt-i18n-routes

Ohter comment

I actually still doesn't well get the configuration structure for this custom routes look like. On the documentation said,

     routes: {
        about: {
          fr: '/a-propos',
          en: '/about-us'
        }
      }

I don't know what was the about key there? Is it the name of the page or what?

This question is available on Nuxt.js community (#c29)

Lazy Load json files after generating static files

Hello!

I was trying around a bit if I can use this plugin for my next project. It is awsome by the way. Could set up routing and translation in about 40 minutes! yay!

But I found one issue. When using "npm run generate" to generate static files - the first page load does not show the translations! If I change the language it starts working. It seems that on inital load the json language file is not working. Does anybody have any clue how i can solve that?

I made a git repo here https://github.com/elpeyotl/nuxt-translation. attached a screenshot of the behaviour.

Well it is only not working when generating static pages. In npn run dev it is working.

nuxt

my config
module.exports = { modules: [ ['nuxt-i18n', { locales: [ { code: 'en', iso: 'en-US', name: 'English', langFile: 'en-US.json' }, { code: 'fr', iso: 'fr-FR', name: 'Français', langFile: 'fr-FR.json' }, { code: 'de', iso: 'de-DE', name: 'Deutsch', langFile: 'de-DE.json' } ], loadLanguagesAsync: true, langDir: 'lang/', defaultLocale: 'en', // ... }] ] }

This bug report is available on Nuxt.js community (#c24)

Translated path

Could you please explain how the language specific paths work. I see it works with a routes property. But how does it work for dynamic nested routes?

This question is available on Nuxt.js community (#c3)

cant read messages from .js files

i make en-Us.js file in lang folder and put this code
export default { "welcome" : "sdfs", account_description: 'Account description', }
but not loaded.
i found problem there
`/**

  • Asynchronously load messages from translation files
  • @param {VueI18n} i18n vue-i18n instance
  • @param {String} lang Language code to load
  • @return {Promise}
    /
    export function loadLanguageAsync (i18n, lang) {
    if (!i18n.loadedLanguages) {
    i18n.loadedLanguages = []
    }
    if (!i18n.loadedLanguages.includes(lang)) {
    const langOptions = i18n.locales.find(l => l.code === lang)
    if (langOptions) {
    const { langFile } = langOptions;
    return import(/
    webpackChunkName: "lang-[request]" */ '~/<%= options.langDir %>'+langFile)
    .then(msgs => {
    i18n.setLocaleMessage(lang, msgs)
    i18n.loadedLanguages.push(lang)
    return
    })
    }
    }
    return Promise.resolve()
    }`

in line
i18n.setLocaleMessage(lang, msgs)

to

i18n.setLocaleMessage(lang, msgs.default)

its true?

This question is available on Nuxt.js community (#c34)

[Nuxt] Error while initializing app TyprError: Object doesn't support property or method 'findIndex'

Hello,

I recently added this module to my project and was running just fine until I tested in IE. I noticed the error in my subject for this ticket. Wanted to know if this is a known issue or if there is a workaround that you recommend?

screen shot 2018-02-12 at 4 49 36 pm

I also checked the example website here: https://nuxt-i18n-example-fzvklkzrln.now.sh/ and I'm getting the same error being thrown. Is there a workaround for this?

screen shot 2018-02-13 at 11 02 53 am

The problem that I'm having is in IE it's killing all my other JS from being called like click events etc...

This question is available on Nuxt.js community (#c36)

Vue-i18n-loader does not work

There is the problem in the main loader. In the documentation of vue-i18n, translations could be defined in the Single page component() by the following configs in the rule's module:

module: {
   rules: [
   {
     test: /\.vue$/,
     loader: 'vue-loader',
     options: {
       loaders: {
         i18n: '@kazupon/vue-i18n-loader'
       }
     }
   },
   // ...
 ]
}

The problem is that we don't use 'vue-loader', we use 'eslint-loader' instead in nuxt project. And adding loaders into the config changes nothing. I tried to define new 'push()' with 'vue-loader', but after that, other loaders works incorrectly. Or maybe Vue-i18n-loader is not adaptive for the SSR, so maybe we need nuxt-i18n-loader. And is there a place to be?

Detect browser language

First of all, thanks for this module, is pretty useful! 👍

Now, it would be great if the module is able to detect the browser language and redirect to the user accordingly, so for example, if my browser has the english language enabled, I'd be redirected to '/en'.

I wrote my own middleware for that:

export default function ({ isHMR, app, store, route, params, req, error, redirect }) {
  if (isHMR) return

  if (req) {
    if (route.name) {
      let locale = req.headers['accept-language'].split(',')[0].toLocaleLowerCase().substring(0, 2)

      if (locale === 'en') { // In my case I just care about English or German but of course that line should be a condition to detect if the locale is part of the locales array in the configuration
        app.i18n.locale = locale

        if (params && Object.keys(params).length === 0 && params.constructor === Object) {
          redirect(app.localePath(app.getRouteBaseName()))
        } else {
          redirect(app.localePath({name: app.getRouteBaseName(), params: params}))
        }
      }
    }
  }
}

But I think it would be better if this can be done by the module itself, maybe as an option in the configuration, something like detectBrowserLanguage: true

What do you think?

This question is available on Nuxt.js community (#c32)

[Feature Request] Generate Proper Language Attribute on Static Generated Nuxt

Problem to Solve

Hi I tried to generate nuxt project using nuxt generate command, then I inspect the source code. I see that the lang attribute on html tag isn't generate according to its locale. For instance if my default language was Indonesia, then all of another language also generate in Indonesia.

Proposed Solution

The language attribute generate according to its locale.

This question is available on Nuxt.js community (#c30)

Cannot access localePath in middleware

I'm making a middleware which redirects users to some pages depending on the store informations. However, I'm lacking localePath to localise the path for the redirect. I expected it to be available as context.app.localePath, but it's not.

More interestingly, it's available at context.app.i18n.vm.localePath but the this context is not correct. localePath is somehow bound to a component which has neither $router or $i18n resulting in an error in i18n.routing.plugin.js

For now I'm running out of idea. I suspect that it might be a problem with nuxt lifecycle between plugins / middleware but it's still obscure.

Versions:
nuxt: 1.3
nuxt-i18n: 2.2.4

This question is available on Nuxt.js community (#c16)

some params is missing when use localePath

My reload params is missing to nuxt-link like this
<nuxt-link :to="localePath({ name: 'foo', params: { foo: 'nice', reload: true } })">
this.$router.push(localePath({ name: 'foo', params: { foo: 'nice', reload: true } }))

It's working fine below. No params are lost.
<nuxt-link :to="{ name: 'foo', params: { foo: 'nice', reload: true } }">
this.$router.push({ name: 'foo', params: { foo: 'nice', reload: true } })

This question is available on Nuxt.js community (#c27)

Adding hreflang alternate links in head

I'm trying to automatically add the hreflang links in the head but it's not that easy.

I moved the locales array outside of the module.exports and added the following code in thenuxt.config.js file and it kinda works:

const locales = [
  { code: 'en', ... },
  { code: 'fr', ... }
]

module.exports = {
  ...
  head: {
    link: [
      ...
    ].concat((function () {
      let alternates = []
      locales.forEach((locale) => {
        alternates.push({
          hid: `alternate-${locale.code}`,
          rel: 'alternate',
          hreflang: locale.code,
          href: `https://example.com/${locale.code}`
        })
      })
      return alternates
    })())
  }
}

However, I didn't find a way to dynamically change the href value. The method switchLocalePath() is not accessible from the nuxt.config.js file and it seems we can't access to this.$route.name too.

Any idea on how to do that? What about nuxt-i18n injecting theses alternate links by default since Nuxt is sold as SEO-friendly out of the box. It would be a great addition to the module.

Finally an unrelated question. Why nuxt-i18n is not a scoped package like the sitemap module for instance @nuxtjs/sitemap?

This question is available on Nuxt.js community (#c4)

Cannot read property 'offsetParent' with seo

Hello, excellent module :)

I have an error with seo option in true, the console shows the following error:

Uncaught TypeError: Cannot read property 'offsetParent' of undefined at vue-meta.js:1080

Dependencies:
Nuxt 1.3.0

This bug report is available on Nuxt.js community (#c10)

Cannot read property 'headers' of undefined after Nuxt Generate

Hello,
another error appears after run npm run generate.

Steps:

  1. try create a new nuxt project like:
    vue init vuetifyjs/nuxt my-project then npm install or yarn

  2. install this nuxt-i18n plugin:
    yarn add nuxt-i18n then add some configuration to nuxt.config.js.

  3. npm run dev works fine.

  4. npm run generate shows many errors: like this:

 ROUTE  /en/pages/about

  TypeError: Cannot read property 'headers' of undefined

  - server-bundle.js:5621 module.exports.__webpack_exports__.default
    server-bundle.js:5621:43

  - server-bundle.js:1902 promisify
    server-bundle.js:1902:15

  - server-bundle.js:1883 middlewareSeries
    server-bundle.js:1883:10

  - server-bundle.js:5465 module.exports.__webpack_exports__.default
    server-bundle.js:5465:81
  1. im sure that the errors from this plugin, i have disabled it from nuxt.config.js, and re run npm run generate and everything works fine.

  2. is this plugin works with npm run generate ?

any help!

This question is available on Nuxt.js community (#c43)

How to a page in current language

Hi there
I have extended Axios in plugins how can I redirect to a page in the current language

  $axios.onResponseError((error) => {
    const code = parseInt(error.response && error.response.status, 0);
    logger.debug(`onResponseError ${code}`);
    if (Number.isNaN(code)) {
      redirect('/server-unreachable');
    }
  });
This question is available on Nuxt.js community (#c33)

Currently breaks if hashes are used in the URL.

E.g.switchLocalePath turns /#intro into /fr#intro/, which results in the following error: DOMException: Failed to execute 'querySelector' on 'Document': '#intro/' is not a valid selector..

This question is available on Nuxt.js community (#c37)

How to redirect the index / after setting noPrefixDefaultLocale

Hello,
i have problem:

  1. i set noPrefixDefaultLocale to false
    in the description:
    By default, paths generated for the default language don't contain a locale prefix, set this option to false to disable this behavior

  2. so the generated routes like this, good:

[
  {
    path: "/en/",
    component: _3237362a,
    name: "index-en"
  },
  {
    path: "/fr/",
    component: _3237362a,
    name: "index-fr"
  }
]
  1. then when starting the app, do not redirect to index it shows 404 page not found error!!!
    http://localhost:port/ -> error
    http://localhost:port/en -> index page with English

  2. what i want is some setting that change the default language after setting noPrefixDefaultLocale: false
    or add another auto generated route like this of the default language:

[
  {
    path: "/",
    component: _3237362a,
    name: "index-en" // the default language!!! or redirectRootToLocale content!!
  },
  {
    path: "/en/",
    component: _3237362a,
    name: "index-en"
  },
  {
    path: "/fr/",
    component: _3237362a,
    name: "index-fr"
  }
]
  1. i think this : redirectRootToLocale: 'en' must work every time.
    the problem as description said:
    Specify a locale to which the user should be redirected when visiting root URL (/), doesn't do anything if noPrefixDefaultLocale is enabled

so make redirectRootToLocale work every time to solve this as i think!!

and thank you :).

This question is available on Nuxt.js community (#c23)

Warning when langDir is not specified

I got some warnings when using nuxt-i18n 2.3.0 with the last version of the starter template.

warning in ./static/robots.txt
Module parse failed: Unexpected token (1:10)
You may need an appropriate loader to handle this file type.
| User-agent: *
| Disallow: /

 @ . lazy ^\.\/.*$
 @ ./.nuxt/i18n.utils.js
 @ ./.nuxt/i18n.plugin.js
 @ ./.nuxt/index.js
 @ ./.nuxt/client.js
 @ multi webpack-hot-middleware/client?name=client&reload=true&timeout=30000&path=/__webpack_hmr ./.nuxt/client.js

I suspect this is due to the regex in the latest lazy loading feature. If you make an error in your configuration, let's say you don't specify the langDir property, then, you will get this error. Maybe, you could prompt a clearer message in such a case.

In async loading mode, if the language file does not exist, there is no error in the terminal.

Hope this can help improve this module.

This question is available on Nuxt.js community (#c14)

Navigating to a non-existent URL with no defaultLocale defined throws a TypeError

I'm trying to create a website with all content shown at example.com/en (or /fr, /es, /it etc.) So basically when you go to example.com, I want to redirect to /en /fr /es.. based on certain parameters, such as cookies and the browser locale.

While trying to figure out a way to do this, the first step was skipping defining a defaultLocale. That way, all my languages are under their respective /locale/ url (it is also necessary to include the trailing slash, otherwise you get the error shown below).

However, when navigating to a non-existent URL without a defaultLocale, you get:

{ TypeError: Cannot set property 'error' of undefined
    at Object.error (.nuxt/index.js:91:0)
    at module.exports.__webpack_exports__.a (.nuxt/i18n.plugin.js:20:0)
    at createApp (.nuxt/index.js:159:0)
    at <anonymous> statusCode: 500, name: 'TypeError' }

Instead of the usual 404 not found that you get with defaultLocale defined.

So what I'm asking is more or less; is this expected behaviour? Are you supposed to always use a defaultLocale? And do you have any suggestion as to how I can achieve what I am trying to achieve?

Ps. Thank you for a truly superb module, the localePath() feature has helped me loads!

This question is available on Nuxt.js community (#c11)

Nuxt build fails with 2.3.0 release

Trying to update to latest release causes nuxt build to fail on missing dependencies, but version 2.2.4 does not have this issue. Also seems like the build is much slower.

This bug report is available on Nuxt.js community (#c22)

How to handle localised dynamic route segments (slugs)

How should localised dynamic route segments be handled or what is recommended?

We fetch articles from an external api and receive articles with available translations (including localised slugs for each available translation). I would like not to use Vuex to "fix" the slug in the global language switch which we use in the default layout.

This question is available on Nuxt.js community (#c18)

Load fallback language when needed (lazy-load)

nuxt-i18n version: 2.3.4

Imagine you have two languages, en (default) and de.
But only parts of the en language is localized in the de file.
If you now enter a page (e.g. /de/only-half-localized-route), you see the correct translations (for de) where it applies, but no en translation because the fallback language isn't loaded properly because of lazy-loading. Instead, you see the translation keys.

A naive fix for it would be to load the fallback language every time, but I guess there is a way to check if a fallback is needed and load the fallback language in that case (if not already loaded).

This feature request is available on Nuxt.js community (#c39)

vue router warning

In all routes with more than one level i have this warning:

[vue-router] Route with name 'usuario-editar-perfil-es-es' does not exist

Examples:

Route: http://localhost:3000/usuario/editar-perfil
[vue-router] Route with name 'usuario-editar-perfil-es-es' does not exist

Route: http://localhost:3000/usuario/mis-anuncios
[vue-router] Route with name 'usuario-mis-anuncios-es-es' does not exist

But in routes with only one level it is okay, for example:

http://localhost:3000/ayuda
http://localhost:3000/quienes-somos

My Nuxt version is 1.4.0 and nuxt-i18n version is 2.9.1.
Configurations:

  defaultLocale: 'es',
  locales: [
    {
      code: 'es',
      iso: 'es-ES',
      name: 'Español',
      langFile: 'es-ES.js'
    },
    {
      code: 'en',
      iso: 'en-US',
      name: 'English',
      langFile: 'en-US.js'
    }
  ],
  loadLanguagesAsync: true,
  langDir: 'locales/'
This question is available on Nuxt.js community (#c44)

Feature request: Custom route keys

Heyho! First of all: Thanks for marking this module 🙏

I'm currently building my companies page with "German" (de) as the default language. So far so good. The only thing that annoys me a bit is that the keys in the routes object should match the base routes from Nuxt. I think it'd be better to use them as custom/general keys.

Currently, my route file would look like this:

routes: {
    'about-us': {
      de: '/über-uns'
    },
    work: {
      de: '/referenzen'
    },
    'some-other-long-route-here': {}
   // ...
  },

It's a bit annoying because I can't keep the route keys short and often I need to "escape" them with quotes (because of the hyphens).

The best case for the routes file would be

routes: {
    about: {
      de: '/über-uns',
      en: '/about-us'
    },
    work: {
      de: '/referenzen',
      en: '/work'
    },
    whatever: {
      en: ' some-other-long-route-here'
    }
  },

Short and meaningful keys, and clear routing that doesn't depend on the actual components.

But I guess that's a lot of work because you'd need to find out the component for each custom route as well. I'm not sure if that's even possible (except you set it in the config)

This question is available on Nuxt.js community (#c5)

Splitting nuxt.cofig

How can i split nuxt.config so that the messages and routes are separate files?

This question is available on Nuxt.js community (#c35)

How to have multiple aliases for the same page?

I want URLs having 2 different patterns to point to the same page:

  • for cars with odd id: /en/car/1, /voiture/1
  • for cars with even id: /en/latest/2, /nouveau/2

(both should render the same /pages/cars/show.vue component)

Could this be implement with the current version? And I wonder how both routes: { ... } object and localePath( ... ) call should look.

Thanks for this module.

This feature request is available on Nuxt.js community (#c20)

Assets and routes

I try to bind my image src attribute and use a path that depends on the current locale:

<img :src="'~/assets/image-' + $i18n.locale + '.svg'">

However it does not work and the output is:

<img src="~/assets/image-en.svg">

Another issue is with video posters, my paths don't work. Any idea?

<video poster="~/assets/poster.png">...</video>

This question is available on Nuxt.js community (#c15)

Locale keep switching to default locale when visit ignore route

How can I prevent locale switch to default when visit ignore route?

Example, my default locale is th my current page is /en/view-blablabla. I go some page that in ignore /settings. I would like it to stay in en but it just switching to th.

Every localized route now is also switched to th too.

This question is available on Nuxt.js community (#c40)

[Feature Request] Use Folder Name Without Index in Custom Routes

Problem to Solve

If I use folder-based routing, i have to write

   'register/index': {
      id: '/masuk',
      en: '/login'
    }

Proposed Solution

Why not just write the name of folder without index as same as for file-based routing,

   'register': {
      id: '/masuk',
      en: '/login'
    }
This question is available on Nuxt.js community (#c31)

Accept async return from language files

What problem does this feature solve?

At the moment its possible to load language files asynchronous using dynamic imports, would be also nice to accept promises as returned value.

This way we can fetch translation messages from an API for example.

Example:

// <lang_dir>/en-US.js
 module.exports = async function() {
     return i18n.getTranslations('en-US'); // returns a promise
};

Also, it would be nice to have a translation message provider option (we could use loadLanguagesAsync to also accept a function):

// nuxt.config.js
{
    modules: [
        ['nuxt-i18n', {
            loadLanguagesAsync: function(langCode) {
                return i18n.getTranslations(langCode); // returns a promise
            }
        }]
    ]
}
This feature request is available on Nuxt.js community (#c50)

How to specify a route for only one language?

Right now the routes are generated per language. How would I specify that I want a route to be available in just one language?

Using _locale as the first param caused some issues before, but at least we could easily separate pages that are localized and pages that should be used as-is.

/pages/_locale/index.vue
/pages/en/styleguide.vue
This question is available on Nuxt.js community (#c1)

Allow to specify glob or regex in ignorePaths

Hi, thanks for the awesome module!

I'd like to propose to add regex as an option for ignorePaths, so that it's possible to ignore, say, the whole subpath (directory in pages, respectively). Extension of #2 and #3

This question is available on Nuxt.js community (#c26)

Warning vue router

In all routes with more than one level i have this warning:

[vue-router] Route with name 'usuario-editar-perfil-es-es' does not exist

Examples:

Route: http://localhost:3000/usuario/editar-perfil
[vue-router] Route with name 'usuario-editar-perfil-es-es' does not exist

Route: http://localhost:3000/usuario/mis-anuncios
[vue-router] Route with name 'usuario-mis-anuncios-es-es' does not exist

But in routes with only one level it is okay, for example:

http://localhost:3000/ayuda
http://localhost:3000/quienes-somos

My Nuxt version is 1.4.0 and nuxt-i18n version is 2.9.1.
Configurations:

  defaultLocale: 'es',
  locales: [
    {
      code: 'es',
      iso: 'es-ES',
      name: 'Español',
      langFile: 'es-ES.js'
    },
    {
      code: 'en',
      iso: 'en-US',
      name: 'English',
      langFile: 'en-US.js'
    }
  ],
  loadLanguagesAsync: true,
  langDir: 'locales/'
This question is available on Nuxt.js community (#c46)

Setting base property in Nuxt's router breaks localePath links.

Setting this property in nuxt.config.js, as per https://nuxtjs.org/api/configuration-router#base:

module.exports = {
  ...
  router: {
    base: '/baseURL/'
  },
  ...
}

When calling:

<router-link :to="localePath('someroute')" />
  • Expected href: /baseURL/locale/someroute (or /baseURL/someroute in case it's the default locale).
  • Getting: /baseURL/baseURL/someroute.

Currently using version 1.1.0, the 2.* versions are crashing for me.

This question is available on Nuxt.js community (#c41)

Handle anchors correctly

I want to use nuxt-i18n to "translate" anchor links (though it might sound weird).

Example config:

 locales: [
    {
      code: 'en',
      iso: 'en-US',
      name: 'English'
    },
    {
      code: 'de',
      iso: 'de-DE',
      name: 'Deutsch'
    }
  ],
  defaultLocale: 'en',
    work: {
      de: '/referenzen'
    },
    '#contact-us': {
      de: '#schreib-uns'
    },

If I iterate over all links and use the localePath function..

  <nuxt-link
          v-for="link in links"
          :key="link"
          :to="localePath(link)">
          {{ $t(`links.link`) }}

the anchor tag isn't resolved correctly. I guess that the problem lies in the export of base routes while ignoring other routes that aren't included in the base routes of Nuxt

This question is available on Nuxt.js community (#c6)

This plugin brokes my font-awsome SSR

When im enabling this plugin with my config my font awesome icons are not loading from SSR and then i will get errors of cliend and server dismatch

My config

['nuxt-i18n', {
      locales: [
        {
          code: 'fi',
          iso: 'fi-FI',
          name: 'Suomi',
          langFile: 'fi.js'
        },
        {
          code: 'en',
          iso: 'en-US',
          name: 'English',
          langFile: 'en.js'
        }
      ],
      defaultLocale: 'fi',
      loadLanguagesAsync: true,
      langDir: '../resources/locales/' // resolve(__dirname, '..', 'resources', 'locales')
    }]

My font awesome plugin

import fontawesome from '@fortawesome/fontawesome'
import {
  faAngleLeft,
  faAngleRight,
  faCloudUpload,
  faEnvelope,
  faEuroSign,
  faHeart,
  faLock,
  faMapMarkerAlt,
  faPencil,
  faPhone,
  faSearch,
  faShoppingCart,
  faTrash
} from '@fortawesome/fontawesome-pro-light'
import {
  faFacebook,
  faFacebookF,
  faInstagram,
  faTwitterSquare
} from '@fortawesome/fontawesome-free-brands'

fontawesome.config = {
  autoAddCss: false
}

fontawesome.library.add(
  // Light
  faAngleLeft,
  faAngleLeft,
  faAngleRight,
  faCloudUpload,
  faEnvelope,
  faEuroSign,
  faHeart,
  faLock,
  faMapMarkerAlt,
  faPencil,
  faPhone,
  faSearch,
  faShoppingCart,
  faTrash,
  // Brands
  faFacebook,
  faFacebookF,
  faInstagram,
  faTwitterSquare
)

export default fontawesome

EDIT: When disabling loadLanguagesAsync: true it works fine.

This question is available on Nuxt.js community (#c17)

Handling dynamic routes with nuxt generate

Firstly a huge thanks for making this module. It's exactly what I was looking for and was hoping I wouldn't have to create.

Is there a recommended way to handle localised, dynamic route generation?

Currently I'm getting route slugs as per the generate docs, then going over the locales and adding prefixes to all the routes. This feels hacky, and I suspect I'm doing it the 'wrong' way since the module already includes a routes config feature, but I couldn't see an obvious way to hook into this.

All the routes get generated properly, except the index page for non-default locales gets output with no filename. It ends up in the right place, but named '.html'. This is only when generate.subFolders is set to false.

This question is available on Nuxt.js community (#c19)

[Bug Report] Breaks when you have extendRoutes defined

First of all great plugin! I found a bug when you define extendRoutes (https://nuxtjs.org/api/configuration-router/#extendroutes) the Nuxt app breaks because of the module. The error it returns in the terminal is as follow:

TypeError: Cannot read property 'replace' of undefined

  - routes.js:42 locales.forEach
    [secrid-nuxt]/[nuxt-i18n]/lib/routes.js:42:40

  - Array.forEach

  - routes.js:39 localizedRoutes.forEach.baseRoute
    [secrid-nuxt]/[nuxt-i18n]/lib/routes.js:39:13

  - Array.forEach

  - routes.js:38 generateRoutes
    [secrid-nuxt]/[nuxt-i18n]/lib/routes.js:38:19

  - module.js:23 Object.extendRoutes
    [secrid-nuxt]/[nuxt-i18n]/lib/module.js:23:23

  - utils.js:119 Object.extendRoutes
    [secrid-nuxt]/[nuxt]/lib/common/utils.js:119:23

  - builder.js:347 Builder.generateRoutesAndFiles
    [secrid-nuxt]/[nuxt]/lib/builder/builder.js:347:50

I created a gist with my Nuxt config: https://gist.github.com/martinrisseeuw/e1ffea12757710c4ff94ef1d95f5cf4b

Do you maybe have a solution or workaround that I can use the module?

This question is available on Nuxt.js community (#c25)

[edge] Content Security Policy: The page’s settings blocked the loading of a resource at self (“default-src”)

I was trying to use nuxt-i18n with the version 2 of Nuxt but I got the following errors:

Content Security Policy: The page’s settings blocked the loading of a resource at self (“default-src”). Source: ;(function(e){let t={};if(e.hasOwnProper....

Content Security Policy: The page’s settings blocked the loading of a resource at self (“default-src”). Source: ;(function(e){setTimeout(()=>{const n=do....

Content Security Policy: The page’s settings blocked the loading of a resource at self (“default-src”). Source: ;(function(e){let n=null,t=0;const o={no....

This question is available on Nuxt.js community (#c53)

Here is my config:

{
  locales: [
    { code: 'en' },
    { code: 'fr' }
  ],
  defaultLocale: 'en',
  vueI18n: {
    fallbackLocale: 'en',
    messages: {
      'en': localesEn,
      'fr': localesFr
    }
  }
}

[V2.2.1] Localized url's are missing '/' at end, defaultLocale is loaded on full refresh

It seems that since V2.2.1 there is no slash added anymore to the localized route, which is a nice feature (because you want to be able to handle '/nl' and '/nl/' , but this doesn't work on initial load: e.g.: it loses the selected language on a full page refresh.

For example: http://example.com/ would load in the default locale ('en'). Switching to another language (e.g. 'nl') changes the route to http://example.com/nl and shows the localized content. However, if I do a full page refresh the route stays on http://example.com/nl but the content is rendered in the default locale again, instead of 'nl'.

It would be nice if both '/nl' and '/nl/' are supported or if '/nl' would always (try to) redirect to '/nl/'

Feature request:
Maybe I should create another issue for this, but I would like to be able to redirect users to a language found in the navigator.languages on initial load. I have a working workaround, also saving the last selected locale in localStorage (so a visitor can still overwrite the default behaviour of redirecting to a matching locale from navigator.languages) and then checking if a returning visitor on the index has a previous language set, but it's not perfect. Any ideas about this?

This question is available on Nuxt.js community (#c12)

Remove lodash from nuxt-i18n middleware

nuxt-i18n version: 2.5.1

With the new language detection feature, lodash was added into the middleware and the front-end bundle. This has some heavy side effects concerning the bundle size:

image

You could also go for importing lodash.has instead of the whole lodash module.

image

This question is available on Nuxt.js community (#c38)

Reload of JSON language files

I store translations in JSON files and configure nuxt-i18n like this:

    ['nuxt-i18n', {
      locales: [locale.language],
      vueI18n: {
        messages: {
          [locale.code]: require('./locales/' + locale.code + '.json')
        }
      },
      defaultLocale: locale.code
    }]

My use case is that I use nuxt generate to generate separate sites for all languages that are served from different domains, so I only specify one language per build.

The problem I'm facing is that changes to ./locales/.json are only visible in the app after I restart the dev server.

Having

    watch: [
      '~/locales'
    ],

in nuxt.config.js does cause the page to reload when I save locales files, but the changes are not visible.

Any thoughs on this?

This question is available on Nuxt.js community (#c28)

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.