Retrieve config and env variable in vue component - javascript

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 ?

To access your env variables in a Vue Component file in Laravel, you will need to prefix your variable with MIX_.
In the .env file
To take your case as an example, if you intend to use APP_URL as a variable in your .env file, instead of APP_URL, you should use MIX_APP_URL like:
MIX_APP_URL=http://example.com
In your Vue Component file
You then access the variable by using the process.env object in your script like:
process.env.MIX_APP_URL
Say today you set a property named proxyUrl and assign the variable as its value, in your script in the .vue file, the code should look like:
export default {
data () {
return {
proxyUrl: process.env.MIX_APP_URL,
},
}
}
After that you should be able to retrieve the property in your vue template as normal like:
<template>
<div>
//To print the value out
<p>{{proxyUrl}}</p>
// To access proxyUrl and bind it to an attribute
<div :url='proxyUrl'>Example as an attribute</div>
</div>
</template>
Here is the official doc released in Laravel 8.x, in case you want to have a look.

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

IMPORTANT
You have to reload the bundle for the changes to take effect.
Mine didn't work until I killed the dev bundle and re-ran npm run watch.

You can do this in Blade template:
let window.something = {{ config('seme_config.something') }}
Then just use the variable in JS with:
window.something
Also, you shouldn't use env() helper directly. Extract data from config file only.

Related

Cannot reach key from .env file

I'm on React.Js and using emailjs to manage contact form. In order to sends the form, I must fill the user-id and template-id. But I don't want it to be visible so I put it on the .env file like that:
REACT_APP_USER_ID= user_id
REACT_APP_TEMPLATE_ID= template_id
To pass these values easely in the sendForm() property, I've put them on variables :
(useContact.jsx)
const template = REACT_APP_TEMPLATE_ID
const user = REACT_APP_USER_ID
But unfortunately with this config the form is not sent.
my folder architecture
[.env, package.json, .gitignore, src/Components/Contact/useContact.jsx]
It works when pass the raw version of the values.
Thank You.
You can access the environment variables by accessing process.env variable like this
const template = process.env.REACT_APP_TEMPLATE_ID
const user = process.env.REACT_APP_USER_ID
Note: you have to restart the server after updating .env file
Env variables are accessible through process.env
It depends how are you loading your .env file, I would suggest you to take a look at dotenv package in order to load your env files
An example you could follow it's the one from this stackoverflow answer

.Environment variables don't work in Vue.js

I have .env file in the root of my project in Vue3. In the components folder, I have Card.vue and this code
console.log(process.env.FOO)
But in browser, it shows undefined.
Variables must start with VUE_APP, hence
`VUE_APP_FOO`
Having a similar problem here. I'm usnig VUE_APP_FOO to set the variable in .env but it's still undefined when console.log(process.env.VUE_APP_FOO).
Using Vue2 (Vue cli 4.5.11)

Structuring js files vue cli project

How should I structure my Vue CLI project? I am unable to find any proper documentation regarding this.
Basically I have around 10 modules and each module has a js file associated with it.
Currently, I am putting all the pages written in my router.js in views directory and all the components in the components directory. I want to know where should I keep mine js files?
All the js api calls associated with every module
JS files containing all the constants related to every module??
Q1: Usually API calls are stored under a respective store if you are using Vuex. If not you can use define them as mixins and use where necessary. The mixins are the parts of the javascript code that are reused in different components. In a mixin you can put any component’s methods from Vue.js they will be merged with the ones of the component that uses it.
Q2: This can definitely go under mixins.
You can also have a util folder (optional) where it contains the functions that you use in components, such as regex value testing, constants, or filters.
Refer to this boilerplate if your project is mid-scale or large-scale.
create a service folder,create service.js -api call goes here(now all you need is to call it when ever you need it)
you have a store folder with store.js(index.js) inside store folder create modules folder
with you modules. inside store.js create modules:[user,event...]
basically that's it. edit your modules files event.js user.js.
you can add getters,mutations,state,actions. just dont forget export const namespaced = true so it`ll go to the global namespace

How to use ts file in external js file

How i can use a ts file in java script file.
I have an angular project in that i have a constant file which is environment.ts file and data is as below
export const Environment = {
PRODUCTION: false
};
and i have used one external java script library and in that library i want to access this environment.ts file i.e want to use constant.
i have tried with
var en = require('./environment.ts');
But not able to access it.
The problem probably comes from the fact that TS is compiled into JS during the build process.
Since you're just exporting the single object, it doesn't really need to be a typescript file.
Try to rename the file into 'environment.js', it shouldn't break anything and it will allow you to require it in other js files.
Try this,
import { Environment } from './environment';
Now we can access the properties like Environment.PRODUCTION
What I did is created dev.json and prod.json with my configurations.
I then imported dev.json into environment.ts and prod.json into environment.prod.ts for exporting to ts files.
I also imported dev.json into an environment.js and environment.prod.js for exporting to js files. You could also use the json directly if you want, but this will give you the flexibility to manipulate in js if you want later.
Now to update configs you just keep updating the json files.
Make sure your external js knows which env configs to read depending on how you're building/compiling it.

Properties file in JavaScript / Angular

In Java I usually create application.properties in my resource folder and put configs in there.
And when I need it I just do Properties prop = new Properties(); prop.load(... my file) and then use prop.getProperty("Something")
I want to do something similar in Javascript
In my js code I have this:
// REST API Base URL
var baseUrl = "http://localhost:8083/api";
I want this to be in a application.properties file and then load the value.
How can I achive this?
Thanks
In angular 2+ projects and for a good practices you should create environments folder with one file per env like: environment.js, environment.prod.js.
and into file you can export a constant or by default like that
export const environment = {
apiUrl: '',
googleApiKey: '',
}
and you can import this environment in every file you will needed like
import { environment } from '{relativePath}/environment/environment.js'
If you create different files for every env like prod. You need to replace environment.js for env that you will be build. You have lot of info about this with webpack or other compilers.
I recommend you strongly to develop into a common.js project. It will be more friendly for you importing modules and you will have powerful possibilities of scalable app.
But the easy(Ugly) solution is:
index.html
<head>
<script src="environment.js">
<script src="app.js">
</head>
environment.js
// Declaring environment like that you will have window scoped the variable
// and you will have global access to environment with window.environment
var environment = {apiUrl: 'https://api.url:4100'}
app.js
function example(){
console.log(window.environment.apiUrl); // out https://api.url:4100
}
The approach depends on how you build and/or bundle your AngularJs application. But regardless of that, you'll need to create a config.json file to contain your settings.
If using browserify or webpack, you can import that file via require(...), otherwise you can simply request it via ajax before your app bootstraps.
In any of these cases, the best way to use the configuration data throughout your app is to define it as a constant at the bootstrap phase: app.constant('CONFIG', configData);, assuming that configData is a variable that contains the data from your config.json file.
Then you can use dependency injection to provide CONFIG to all your controllers, services and directives.

Categories

Resources