PublishedDate: 09 May 2025

安裝 @nuxtjs/i18n v8

NuxtI18n官網
Vue-I18n

nodejs 多國語言的套件非常複雜,有很多專案寫到一半就放棄了,太多陷阱。vue-i18n 與 @nuxtjs/i18n 是同一套語言檔可以共用,設定當也差不多,但是唯一差別的是 vue-i18n 是支援 webpack,沒試過在 nuxt 可不可以使用。 @nuxtjs/i18n 專門為 nuxt 使用的 module ,之前使用 vue-i18n 幾乎可以無痛更新。

安裝與設定

1.安裝

注意: , v8 與 v9 的設定不相同,本範例使用 v8 版本。

npx
npx nuxi module add @nuxtjs/[email protected]

2.設定

加入 module

nuxt.config.ts
// nuxt.config.ts
export default defineNuxtConfig({
  future: {
    compatibilityVersion: 4,
  },
  modules: ['@nuxtjs/i18n'], // v8
  i18n: {
    vueI18n: './i18n.config.ts' // if you are using custom path, default
  }
})

加入 i18n 設定檔案

方法一

i18n.config.ts
// i18n.config.ts
export default defineI18nConfig(() => ({
  legacy: false,
  locale: 'en',
  // v8
  messages: {
    en: {
      welcome: 'Welcome to z5525.com'
    },
    fr: {
      welcome: 'Bienvenue z5525.com'
    },
    zh_Hant: {
      welcome: '歡迎光臨 z5525.com'
    }
  }
}))

方法二

用 json 語法產生語言檔,個人喜歡用 yaml 語言檔,發布之前轉換成 json 語言檔案。

locales/en.json
{
  "hello": "Hello World!",
  "welcome": "Welcome to z5525.com"
}
locales/fr.json
{
  "hello": "Hello World!",
  "welcome": "Bienvenue z5525.com"
}
locales/zh_Hant.json
{
  "hello": "你好,世界!",
  "welcome": "歡迎來到 z5525.com"
}

最後將語言檔匯入到 i18n.config.ts 設定檔案

i18n.config.ts
// i18n.config.ts
import en from './locales/en.json'
import fr from './locales/fr.json'
import zh_Hant from './locales/zh_Hant.json'
export default defineI18nConfig(() => ({
  legacy: false,
  locale: 'en',
  messages: {
    en: en,
    fr: fr,
    zh_Hant: zh_Hant
  }
}))

測試頁面

1.在 pages 加入一個頁面

app/pages/i18n-demo.vue
<!-- app/pages/i18n-demo.vue -->
<script setup>
const { locale, setLocale } = useI18n()
</script>

<template>
  <div>
    <h1 class="p-4 bg-red-500">z5525.com</h1>
  </div>
  <div>
    <div class="p-4 flex gap-4">
      <button @click="setLocale('en')">en</button>
      <button @click="setLocale('fr')">fr</button>
      <button @click="setLocale('zh_Hant')">zh_Hant</button>      
    </div>
    <div class="p-4">
      <p>{{ $t('welcome') }}</p>
    </div>
  </div>
</template>

i18n展示

專案目錄檔案

錯誤資訊

@intlify/nuxt3

參考資料 Reference

NuxtI18n 官網vue-i18n

版本備註

nuxt v3.15.4 @nuxtjs/i18n v8.5.6