苗条的框架:苗条的应用程序中不出现环境变量 [英] Svelte framework: environment variables not appearing in svelte app

查看:97
本文介绍了苗条的框架:苗条的应用程序中不出现环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的Svelte应用程序中使用环境变量.我已经安装了 @ Rollup/plugin-replace dotenv .我创建了一个 .env 文件来保存我的 API_KEY ,并将以下内容添加到 rollup.config.js 中的 plugins 中来自此中文章:

I'm trying to use environment variables in my svelte app. I've installed @Rollup/plugin-replace and dotenv. I created a .env file to hold my API_KEY and added the following to plugins in rollup.config.js from this Medium article:

plugins: [
  replace({
    __myapp: JSON.stringify({
      env: {
        isProd: production,
        API_URL : process.env.API_URL
      }
    }),
  }),
]

在我的应用程序的精简组件中,我将通过

and in the svelte components of my app I would access my API key via

const apiUrl = __myapp.env.API_URL

有效.但是,几天后,我遇到了身份验证问题,经过调试后,我发现 __ myapp.env.API_URL 通过尝试将其打印到控制台而返回了 undefined .

which worked. However, a few days later I was having authentication issues and after some debugging I found that __myapp.env.API_URL was returning undefined by trying to print it to the console.

然后我尝试将 replace 调用更改为 replace({'API_KEY':process.env.API_KEY}) console.log(API_KEY)仍显示 undefined .我通过尝试使用 replace 来替换某些变量,并使用某些字符串来测试 replace ,它可以正常工作,从而确认汇总是否可以正常工作.因此,我怀疑问题出在 process.env.API_KEY 中,但我不确定.尝试访问环境变量可能会出错吗?

I then tried changing the replace call to just replace({'API_KEY': process.env.API_KEY}) and console.log(API_KEY) was still displaying undefined. I tested replace by trying to use it replace some variable with some string and it worked so that confirms that rollup is working fine. So, I suspect the problem is in process.env.API_KEY but I'm not sure. What might I be doing wrong with my attempts to access my environment variables?

(某些背景:我正在使用 sveltejs/template 作为模板来构建我的应用程序)

(Some background: I am using sveltejs/template as a template to build my app)

推荐答案

dotenv 在您调用 config .env 变量.>,这就是为什么当您尝试访问 process.env.API_KEY 时未定义的原因.

dotenv won't register your .env vars until you call config, that's why process.env.API_KEY is undefined when you try to access it.

在您的 rollup.config.js 中,您可以执行以下操作:

In your rollup.config.js you can do:

import { config as configDotenv } from 'dotenv';
import replace from '@rollup/plugin-replace';

configDotenv();

export default {
   input: 'src/main.js',
   ...
   plugins: [
    replace({
      __myapp: JSON.stringify({
        env: {
          isProd: production,
          API_URL: process.env.API_URL,
        },
      }),
    }),
    svelte({ ... })
   ]
}

这篇关于苗条的框架:苗条的应用程序中不出现环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆