如何在Nuxt中访问.js文件中的环境变量



我有以下文件:

// nuxt.config.js
import { locales } from './services/i18n'
...
i18n: {
lazy: true,
langDir: '~/locales/',
defaultLocale: 'en',
detectBrowserLanguage: false,
differentDomains: true,
locales,
vueI18n: {
fallbackLocale: 'en'
}
},
publicRuntimeConfig: {
...
subDomain: process.env.SUB_DOMAIN,
},
...

// services/i18n/index.js
export const locales = [
{
code: 'ar',
iso: 'ar',
file: 'ar.json',
dir: 'rtl',
domain: `${process.env.SUB_DOMAIN}.example.ae`,
name: 'العَرَبِيَّة',
enName: 'Arabic',
defaultLanguage: true,
languages: ['ar']
},
{
code: 'bg',
iso: 'bg',
file: 'bg.json',
dir: 'ltr',
domain: `${process.env.SUB_DOMAIN}.example.bg`,
name: 'Български',
enName: 'Bulgarian',
defaultLanguage: true,
languages: ['bg']
},
...
]

问题是process.env.SUB_DOMAIN/services/i18n/index.js中似乎是未定义的,尽管它是因为nuxt.config.js中没有定义相同的变量而设置的。我知道nuxt将publicRuntimeConfig的值公开为$config,但是,$config/services/i18n/index.js中是不可访问的。如果我将locales移动到nuxt.config.js,这可能会起作用,但我不想这样做,因为这会降低配置文件的可读性。

因此,我的问题是在/services/i18n/index.js中获取子域的最佳方法是什么。

编辑:Alexander Lichter在Nuxtjs的讨论中给出了一个很好的答案:https://github.com/nuxt/nuxt.js/discussions/9289#discussioncomment-729801
// nuxt.config.js
import { locales } from './services/i18n'
...
i18n: {
lazy: true,
langDir: '~/locales/',
defaultLocale: 'en',
detectBrowserLanguage: false,
differentDomains: true,
locales: locales(process.env.SUB_DOMAIN),
vueI18n: {
fallbackLocale: 'en'
}
},
publicRuntimeConfig: {
...
subDomain: process.env.SUB_DOMAIN,
},
...
// services/i18n/index.js
export const locales = domain => [
{
code: 'ar',
iso: 'ar',
file: 'ar.json',
dir: 'rtl',
domain: `${domain}.example.ae`,
name: 'العَرَبِيَّة',
enName: 'Arabic',
defaultLanguage: true,
languages: ['ar']
},
{
code: 'bg',
iso: 'bg',
file: 'bg.json',
dir: 'ltr',
domain: `${domain}.example.bg`,
name: 'Български',
enName: 'Bulgarian',
defaultLanguage: true,
languages: ['bg']
},
...
]

最新更新