'VueJS environment variables not usable in main.js

I have a main.js file in my app, and I use something called XXX (the name is not relevant here). I try to use environment variables to configure XXX:

app
  .use(XXX, {
    host: process.env.VUE_APP_XXX_URL,
    siteId: process.env.VUE_APP_XXX_SITE_ID,
    router,
  })

But it doesn't work. When I use the real values, it works like a charm. I think I can't use environment variables in my main.js file. What would be the good solution?

PS: https://cli.vuejs.org/guide/mode-and-env.html#using-env-variables-in-client-side-code doesn't work either

Thanks in advance.



Solution 1:[1]

You can use dotenv npm package for custom environment variables.

Usage

Create a .env file in the root of your project:

VUE_APP_XXX_URL="Your URL"
VUE_APP_XXX_SITE_ID="Your Site ID"

As early as possible in your application (For example in main.ts or main.js), import and configure dotenv:

require('dotenv').config()

After that you can now get your custom environment variable in process.env object.

process.env.VUE_APP_XXX_URL; // Your URL
process.env.VUE_APP_XXX_SITE_ID; // Your Site ID

Read more in the official package.: dotenv

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Maverick Fabroa