Retrieve config and env variable in vue component Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Retrieve config and env variable in vue component without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I have a Vue component in my Laravel application.

I want to retrieve a URL that is in a config (or the .env Laravel file) directly in my Vue component, instead of hardcoding it. In webpack laravel mix I can retrieve my .env variable like this.

require('dotenv').config() let proxyUrl = process.env.APP_URL

But when I want to do this in my app.js, I have a can't resolve fs when trying to require dotenv.

What is the best way to have this data available in my Vue components ?

Answer

I had this same issue, but placing the variable in blade was not an options for me, also it meant having a variable declare in a blade file and then use in a javascript file which seems a bit unorganized. So if you are in this same position then I think there is a better solution. If you are using Vue you most likely are compiling your files using Laravel mix.

If this is the case you can inject environment variables into Mix, you just need to add the prefix MIX_. So you can add to your .env file a variable like:

MIX_SENTRY_DSN_PUBLIC=http://example.com

and then access this variable like this in your javascript file:

process.env.MIX_SENTRY_DSN_PUBLIC

you can access this anywhere in your pre compile file. You can find this information in the laravel documentation. https://laravel.com/docs/5.6/mix#environment-variables

We are here to answer your question about Retrieve config and env variable in vue component - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji