简体   繁体   English

如何使用 Vue 前端和 rails 后端实现 env vairables? 是否需要使用 dotenv package 来完成此任务?

[英]How do I implement env vairables with a Vue front-end and a rails backe-end? Is it necissary to use the dotenv package to complete this task?

I started working on a project the has some API keys that need to be protected.我开始从事一个项目,该项目有一些需要保护的 API 密钥。 My personal projects are all using React and Node, but this project is built using yarn (which I'm unfamiliar with).我的个人项目都是使用 React 和 Node,但是这个项目是使用 yarn(我不熟悉)构建的。 I have ran yarn add dotenv already, and I've tried using their documentation to get it up and running.我已经运行了yarn add dotenv ,并且尝试使用他们的文档来启动并运行它。 All of the console.log(process.env.***) return undefined .所有的console.log(process.env.***)都返回undefined

My method so far has been to add my variables to the.env file found in the root of the project, and add require('dotenv').config() to the project's application.js file to be loaded.到目前为止,我的方法是将变量添加到项目根目录中的 .env 文件中,并将require('dotenv').config()添加到要加载的项目的application.js文件中。 I read that Vue.js 3 doesn't require dotenv and instead uses _VUE_APP prepended to the variable name (which I've tried to make sure it doesn't work that way with Vue 2.8. Spoiler, it does not).我读到 Vue.js 3 不需要 dotenv 而是使用 _VUE_APP 附加到变量名(我试图确保它不能与 Vue 2.8 一起工作。剧透,它没有)。

Is there a step I'm missing?有没有我错过的步骤? Should I take a different approach altogether?我应该完全采取不同的方法吗?

Thanks in advance!提前致谢!

Lets suppose you have two environments: development and production .假设您有两个环境:开发生产

For having the variables for these environments, create one file for each environment in the root folder (where is the package.json or .gitignore ), one file called .env.development and the other called .env.development , and then just create the variables there.要为这些环境创建变量,请在根文件夹中为每个环境创建一个文件(其中package.json.gitignore ),一个名为.env.development的文件,另一个名为.env.development ,然后只需创建那里的变量。

For example, let's say we want one environment variable called api-path , so create a variable in each file called VUE_APP_API_PATH (for example in development environment VUE_APP_API_PATH = http://localhost:3000 ).例如,假设我们想要一个名为api-path的环境变量,因此在每个名为VUE_APP_API_PATH的文件中创建一个变量(例如在开发环境中VUE_APP_API_PATH = http://localhost:3000 )。

Then, you can retrieve these environment values with let API_route = process.env.VUE_APP_ROOT_API in the script you need this value.然后,您可以在需要此值的脚本中使用let API_route = process.env.VUE_APP_ROOT_API检索这些环境值。

More info here: https://cli.vuejs.org/guide/mode-and-env.html#environment-variables更多信息在这里: https://cli.vuejs.org/guide/mode-and-env.html#environment-variables

Hope it helps.希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM