简体   繁体   中英

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. My personal projects are all using React and Node, but this project is built using yarn (which I'm unfamiliar with). I have ran yarn add dotenv already, and I've tried using their documentation to get it up and running. All of the console.log(process.env.***) return 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. 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).

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.

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 ).

Then, you can retrieve these environment values with let API_route = process.env.VUE_APP_ROOT_API in the script you need this value.

More info here: https://cli.vuejs.org/guide/mode-and-env.html#environment-variables

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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