首页 > 解决方案 > 如何为静态资产文件配置 nuxt-i18n?

问题描述

请注意,我在根“静态”目录中包含一些 js 文件,如下所示。

head: {
script: [{
    type: 'text/javascript',
    src: 'js/jquery.min.js',
    body: true
  },
  {
    type: 'text/javascript',
    src: 'js/bootstrap.min.js',
    body: true
  },
  {
    type: 'text/javascript',
    src: 'js/slick.min.js',
    body: true
  },
  {
    type: 'text/javascript',
    src: 'js/script.js',
    body: true
  }
]},

配置i18n如下

i18n: {
    locales: [{
        code: 'en',
        name: 'English',
        file: 'en-US.js'
      },
      {
        code: 'ar',
        name: 'Arabic',
        file: 'ar-AR.js'
      }
    ],
    defaultLocale: 'en',
    lazy: true,
    langDir: 'lang/',
    defaultLocale: 'en',
    vueI18n: {
      fallbackLocale: 'en'
    }
  },

使用 en 加载我的 js 文件没有问题,但是当我从 en 切换到 ar 时,浏览器控制台为我提供了静态目录中所有包含文件的以下错误。

GET http://localhost:3000/ar/js/jquery.min.js net::ERR_ABORTED 404 (Not Found)

在此处输入图像描述

标签: nuxt.jsserver-side-renderingnuxt-i18n

解决方案


不确定设置为英语时它是如何工作的,但如果你有langDir: 'lang/',你的文件应该位于项目的根目录中的目录中(与等lang处于同一级别)。package.jsonnuxt.config.js

我什至不确定第一个片段是什么。

这是我的nuxt-i18n配置

[
  'nuxt-i18n',
  {
    defaultLocale: FRENCH_LOCALE,
    detectBrowserLanguage: {
      useCookie: true,
      cookieKey: 'detected_locale',
      fallbackLocale: FRENCH_LOCALE,
    },
    strategy: 'no_prefix',
    vueI18n: {
      fallbackLocale: FRENCH_LOCALE,
      silentFallbackWarn: process.env.NODE_ENV === 'production',
      silentTranslationWarn: process.env.NODE_ENV === 'production',
      warnHtmlInMessage: 'error',
      escapeParameterHtml: true,
    },
    vueI18nLoader: true,
    vuex: {
      syncLocale: true,
      // syncMessages: true,
      syncRouteParams: false,
    },
    lazy: true, // not really working: https://github.com/nuxt-community/i18n-module/issues/905
    langDir: 'locales/',
    locales: [
      {
        code: 'en',
        file: 'en.json',
        iso: 'en',
      },
      {
        code: 'fr',
        file: 'fr.json',
        iso: 'fr',
      },
    ],
  },
],

我的 i18n 文件位于/locales根级别。 在此处输入图像描述

PS:我不确定您为什么在文件夹中公开提供您的static文件。有什么具体原因吗?


编辑以回答评论中的一些问题。

static目录用于共享一些公共文件,这些文件可以被搜索引擎、一些网站图标等访问。它们用于加载任何类型的脚本。

像 Boostrap 之类的包,可以通过官方模块的方式访问,这里是官方文档中的一个例子:https ://bootstrap-vue.org/docs#nuxtjs-module 。这是为了对 Nuxt 的一些包进行快速简单的设置。

如果您想将包添加到整个应用程序,您可以直接在head-script. 这通常不是推荐/官方的方式,也不应该用于从 CDN 加载某些库(尤其是jQuery在 Nuxt 应用程序中)。


当然,以上 3 段都与如何配置语言环境完全nuxt-i18n无关,只是为了清楚起见。


推荐阅读