简体   繁体   中英

Vue-cli 3 Environment Variables all undefined

I've tried all of the solutions out there but none seem to work for me. I just want to store some values in a .env file within my Vue app but simply trying to log process.env returns an empty object from within the component.

My .env file

VUE_APP_URL={api url}
VUE_APP_TOKEN={token}

My plan was to set these environment variables to data properties but it always returns undefined . If I do console.log(process.env.NODE_ENV) from webpack.config.js it will show that I'm in development but if I tried doing the same from within the component like

mounted() {
    this.$nextTick(() => {
      console.log(process.env.VUE_APP_URL);
    })
  }

It just returns undefined .

A few tips for people who land here:

  1. Make sure your .env files are in the project root folder (and not in say src/ )
  2. Variable names should start with VUE_APP_ if to be statically embedded into the client bundle
  3. Restart the dev server or build your project for changes to take effect
  4. If you are migrating from a webpack based solution make sure that you replace : (from JSON config) with = ( dotenv format ). Easy to miss
  5. Make sure you've saved any changes to your .env files.
  6. In old Vue versions environment variables were defined in eg config/dev.env.js instead of the .env files in root

我想通了 - 我必须安装dotenv-webpack并在 webpack.config.js 中初始化它,这很奇怪,因为没有一个文档说明我需要这样做。

so I use VUE_APP_API_URL (this doesn't work) then I change it to VUE_APP_APIURL (this works)

hope it helps

If your vue-cli version is higher than 3.x and you put your .env files in root directory like said in comments. Than you can access your environmental variables from components (like this process.env.VUE_APP_YOUR_VARIABLE ). As said in vue-cli docs

Only variables that start with VUE_APP_ will be statically embedded into the client bundle with webpack.DefinePlugin . You can access them in your application code: console.log(process.env.VUE_APP_SECRET)

Install dotenv-webpack and configure the vue.config.js file as follows.

npm install dotenv-webpack --save-dev

Add this to your config file:

const Dotenv = require('dotenv-webpack');


module.exports = {
  configureWebpack: {
    plugins: [
      new Dotenv()
    ]
  }
}

In your .env file make sure you add VUE_APP_ before your variables like this:

VUE_APP_VAR1=example
VUE_APP_VAR2=value

Now you can access these variables in your Vue application:

console.log(process.env.VUE_APP_VAR1); // "example"
console.log(process.env.VUE_APP_VAR2); // "value"

Here some links for reference:

I put my .env file in the root directory and appended each variable with VUE_APP_ .

To demonstrate this, for example, if the variable you want to use is API_BASE_URL

In your .env file, you put the variable as VUE_APP_API_BASE_URL=baseurl/api/v1

To access it in your files, you do process.env.VUE_APP_API_BASE_URL .

CAVEAT:

Never put any sensitive information you don't want anybody to see, on your front-end. The most common thing you won't want anybody to see (as regards web development) is your API Key. There are real consequences to doing this. This is one such example of someone who has been burned exposing API keys to the public.

However, even if you put your sensitive data in a .env file and add the .env file to a .gitignore file (hence not pushing it to a Git repository hosting service eg Github, BitBucket, Gitlab etc.), your data is still not safe on the front-end. It's only safe when this is done on back-end code as it will be hosted on a server.

In the front-end, anyone who is determined enough can find your sensitive information. All your information is available on a browser and all that person needs to do is to open the dev tools and check the Sources tab, and BOOM all your sensitive information is laid bare.

Environment variables on the front-end are only useful when you want one reference point for NON-SENSITIVE information, such as a BASE URL, as seen in the example above. A BASE URL can change during the course of development and you won't want to change all references in the application folder manually. It is tedious plus you may miss a few, which would lead to errors.

If you want to avoid exposing your API keys and other sensitive information you may require on the front-end, take a look at this article .

This is what worked for me. I previously created my .env.development and .env.production files in the root folder by manually by right-clicking in the Exploer in VS Code and adding a new file. This kept giving me undefined.

I deleted the files and first installed npm install touch-cli -g Once installed, i added the environment files as such touch .env.production and touch .env.production and itworks. So I think there's a difference between how these env files are generated.

NOTE: I do not have webpack installed. Just using the vue cli to build

VS Code Explorer Chrome Developer Tools

Vue CLI dotenv usage suffers the inability to provide the .env variables other than prefixed with VUE_APP_ . This is OK but this is far not enough to satisfy any even little serious web project that wants to conveniently and securely manage its (sometimes huge list of) variables for different environments.

Here is the solution that makes use of .env variables as convenient as on backends with dotenv .

With this solution you could access your MY_EXTERNAL_API_KEY from your .env.[environment] file in your code like this const key = process.env.MY_EXTERNAL_API_KEY .

It provides:

  1. The convenience of using non-prefixed with VUE_APP_ variables' names and use .env variable expansion feature (use ${VARNAME} kind of variables)
  2. The necessary security: your variables are neither available at browser console with console.log(pocess.env.MYVAR) at run time nor are explorable via text search within the built application's JS bundle.
  3. You can still use original Vue CLI solution along;

For this use dotenv-webpack plugin in your vue.config.js as follows:

const Dotenv = require('dotenv-webpack');

const envPath = function() {
    return (!process.env.NODE_ENV || (process.env.NODE_ENV === 'development')) ?
        './.env' :
        `./.env.${process.env.NODE_ENV}`;
}

const dotenvArgs = {
    expand: true,
    path: envPath()
};

module.exports = {
   //... some other config here
    configureWebpack: {
        plugins: [
            new Dotenv(dotenvArgs)
        ]
    }
};

Here:

There are other useful dotenv-webpack options you could use.

I believe this solution is good enough to fully satisfy most frequent use cases.

NB: Remember as you pass your secret variables with HTTP requests from your front-end (eg an API key in a call to some external API) they are visible to any one who knows where to look. To diminish security risks for this situation there are different solutions.

Just to hint you have either to:

  • provide only publicly open data via your application;
  • or authenticate your application (or parts of it) via some authentication service (login/password + JWT|sessions, external authentication providers eg Facebook, Google etc.);
  • or resort to server-generated application.

But this is the whole separate subject.

I know that this question was asked about vue-cli 3, which generates code for Vue 2. But it is the top result if you google for "vue3 does not embed env" and similar queries, so I assume that a lot of people end up here when having trouble with process.env variables being undefined in their Vue 3 app.

So this is an answer about how to fix your Vue 3 env issues.

This is what causes the confusion

  1. If you google for env problems with vue, you end up in the vue-cli docs . But vue-cli was replaced by create-vue in Vue 3. There is a alert box at the top of the page that tells you this, but you've probably missed it.

  2. If you did not miss it and followed one of the two links in the box, you ended up in the Vue 3 tooling guide or in the create-vue repo. None of those resources mention env variables. But you learn that create-vue is based on Vite.

  3. If you follow that lead and google for "vite env", you end up in the vite documentation , where you finally find the answer:

    • env variables have to be prefixed with VITE_ to be compiled into the app (as opposed to VUE_APP_ in vue 2 )
    • env variables will be available in import.meta.env in your app (as opposed to process.env in vue 2 )

The latter one is what took me the longest to figure out.

This is how you need to do it

in an .env file in your project root:

VITE_MY_ENV_VAR=foo

The docs will also tell you about the different naming patterns for.env files in Vite. Very useful information if you work with different environments!

in your app:

const my_env_var = import.meta.env.VITE_MY_ENV_VAR

I hope this saves someone the time for figuring this out.

它也可能有帮助:确保你的 .env 文件是小写字母,因为在 Linux 中它不会工作,即使它在 Windows 中工作

The answer provided here helped me out. I'm using Laravel with an odd setup for Vue 2.x. The project is also using Laravel Mix. Here's the solution:

Inside of your .env file, which is a sibling of package.json:

MY_ENVIRONMENT_VARIABLE=my_value

Inside of webpack.mix.js:

const { mix } = require('laravel-mix');

mix.webpackConfig(webpack => {
    return {
        plugins: [
            new webpack.EnvironmentPlugin (
                ['MY_ENVIRONMENT_VARIABLE']
            )
        ]
    };
});

Afterwards, an npm run dev or npx mix should allow you to use these variables.

Credit: Thorsten Lünborg

if you are cominng from VUE-cli-2 or you just cloned/installed an old vuejs project and you can't find .env file, this article explains what you have to do to set your .env variables as they environment files are probably located in config/dev.env.js (Note: this is peculiar to Vue-cli-2 files)

Here is also a solution and a detailed explanation for Vue-cli-3 .env related issue

What worked for me was changing from .env to .env.local . Haven't investigated WHY but I checked an old project and saw that I had a .env.local instead and did same for this project that would not pick the values from .env irrespective of whether vars where prefixed with VUE_APP and it worked.

It seems environment variables are not accessible in child Vue components. Best to declare them globally in main.js with Vue.prototype.env = process.env;

IF you are using VITE, use VITE_ in stead of VUE_APP

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