簡體   English   中英

如何在 Nuxt 中訪問 a.js 文件中的環境變量

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM