![](/img/trans.png)
[英]How to get Nuxt.js environment variables defined in `env` object?
[英]How to access environment variables in a .js file in Nuxt
我有以下文件:
// 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']
},
...
]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.