configurable vue frontend application - javascript

Im working on a Vue frontend that consumes a backend API that are both being deployed to the same kubernetes cluster. I would like to make the vue frontend application configurable so I can assign the address to the backend service on container startup instead of during build time.
I've been trying to do this by following Hendriks answer to this thread:
Pass environment variable into a Vue App at runtime
Due to my lack of Node and Javascript experience, I do not understand the following:
Where in the filestructure the files should be placed?
Why the config.js describes a function, and not just as export default { configObj: var } an object with the variables?
How I can access the variable in config.js through /config.js in the rest of my app? I can see the file in my browser at /config.js, but imports does not work.
I've currently placed the files like so:
/app
/public
index.html << I put the script tag in the head of this file.
...
/src
/config
config.js
main.js << setting axios.defaults.baseURL here. import config from '#/config/config.js' results in the str 'config.js'.
...
vue.config.js
Even though I know my backend service IPs/addresses are not supposed to change in production, setting these values before build seems like a very static and manual way to do it. During development running the app and backends locally on minikube, waiting for long builds quickly becomes very time consuming.
Very greatful for any insight in how I can achieve this, or any insight into why I can't seem to get Hendriks proposal to work.

It's important to note that what you are trying to do doesn't have anything to do with node. The execution environment of your Vue app is going to be the browser and not node (even if you are serving it with node). This is also why you can't do export default of your config, as some browsers won't understand that.
But here is a method you can use in order to get the config to your app using k8s.
Create a k8s config map, which will contain your config.js, something like:
apiVersion: v1
kind: ConfigMap
metadata:
name: vue-config
data:
config.js: |
function config () {
return { serverAddress: "https://example.com/api" };
}
Then in your pod/deployment embed the file:
apiVersion: v1
kind: Pod
spec:
containers:
- name: your-vue-app
image: your-vue-app:1.0.0
volumeMounts:
- name: config-volume
mountPath: /app/public/config.js
volumes:
- name: config-volume
configMap:
name: vue-config
Note that you are putting the config in the public directory. After that you can add the script tag in the index, which loads the config.js. Having the config as a function is useful, because you ensure some level of immutability, also I think it looks a bit better that a global config var.
When you want to use the configuration, you just call the config function anywhere in your configuration:
const conf = config();

Related

Use configuration file to initialize a node_modules library

I made a react component library that I would like to use in multiple projects.
I need to use different variables depending on the environments, for this reason I was thinking of using an initialization file (eg: my-library.init.js) in the host app that exports a config variable, but I don't know how to make the library read this variable from host app.
the file should look like this:
export const config = {
envs: {
S3_URL: 'https://my.dev.url.org'
ENV: 'dev'
}
}
Any help will be appreciated
Tahnk you

How can I bundle an entire Vue app as a single UMD module

I want to bundle a vue app with the styles and everything into a single UMD javascript module using vue-cli-service so that I can import it into another Vue app via my component distribution server. I am able to do this with one component on the serve, but I don't know how I'll be able to bundle an entire app and load it remotely into a separate app. I use this article as a guide https://markus.oberlehner.net/blog/distributed-vue-applications-loading-components-via-http/
This is where I am importing it:
{
path: '/games',
component: GamesHome,
children: [
{
path: 'fun',
component: () =>
externalComponent(
'http://localhost:8200/game/Game.cd590421a6d6835e7ae2.umd.min.js'
),
name: 'Fun Game'
}
] }
So basically how do I create a Vue app then bundle it entirely with CSS and all using vue-cli-service
This is the problem which I have been trying to solve from day 1 ever since I started using VueJS. I will not consider a client side JS framework if it does not provide a solution for this problem.
I recently did a PoC in this and able to consume a VueJS application as module in another VueJS application. In my case I have a suite of VueJs applications where each of these applications is running in its own dedicated docker container. These applications have a lot of functionality which is common across all the applications. So I decided to move this common code (page layout, css frameworks etc) to a separate VueJS application and consume all existing VueJS applications as modules in this global application. I call this micro-app based architecture to differentiate it from micro-frontends based architecture because it does not use multiple client side JS frameworks and does not require another framework to achieve this. This is how the deployment architecture looks like in my case (you can ignore kubernetes specific stuff if your are not aware about it) -
Coming back to implementation part, you need to take a step wise approach to convert a VueJS application to a micro-app.
Lets say you project structure look as following (it shows only few files which require changes and NOT all the files) -
app-1
public
index.html
src
main.js
App.vue
router
index.js
store
index.js
Split your vuex state and routes files into global and application specific files -
app-1
public
index.html
src
main.js
App.vue
router
app1
index.js
index.js
store
app1
index.js
index.js
Make a copy of this project (global-app), remove global-app specific files from app-1 and app-1 from specific files from global-app. Also remove index.html and App.vue from app-1 project -
Add ROUTES and STORE_MODULES variables to index.html file of global-app -
<head>
....
....
<script type="text/javascript">
const ROUTES = []
const STORE_MODULES = {}
</script>
</head>
<body>
....
....
<div id="app"></div>
<script type="text/javascript" src="/app1/micro-app.umd.min.js"></script>
<!-- built files will be auto injected -->
</body>
Update router\index.js file of global-app for ROUTES variable -
const routes = [
....
....
]
routes.push(...ROUTES)
const router = new VueRouter({
Update store\index.js file of global-app for STORE_MODULES variable -
export default new Vuex.Store({
....
....
modules: STORE_MODULES
})
Clear content of app-1\src\main.js file and replace it with following content -
import routes from '#/router/app1'
import app1 from '#/store/app1'
ROUTES.push(...routes)
STORE_MODULES['app1'] = app1
Define build-app command under scripts block of package.json file of app-1 -
....
"scripts": {
"build-app": "vue-cli-service build --target lib --formats umd-min --no-clean --name micro-app src/main.js"
},
....
Now build and deploy these two applications in their dedicated containers and update nginx conf file of proxy container to forward requests to these containers as following -
location / {
proxy_pass http://global-app:80;
}
location /app1/ {
proxy_pass http://app1:80/;
}
You can access global app by using IP address and port of nginx container.
I hope I have included all the steps which are required to implement micro-app based architecture. You can refer following git repositories which were created as part of this PoC -
https://github.com/mechcloud/large-app-docker
https://github.com/mechcloud/large-app
https://github.com/mechcloud/large-app-plugin1
While I am not an expert in the internals of client side JS frameworks, I believe this approach will work for other JS frameworks (Angular, React etc) as well.

Enviroment variables react

I have a react component which in development will redirect to a localhost url but in production to a different url. In my backend I have the same situation and there i solved it with a package called dotenv. I was wondering how someone would do this in a react front-end.
export default withRouter(function Login(props) {
useEffect(() => {
if(localStorage.getItem('jwt')){
props.history.push('/dashboard');
}
})
const handleLogin = () => {
window.location.href = "http://localhost:8000/auth/google";
}
return (
<LoginView handleLogin={handleLogin}/>
)
})
You can use dotenv to add environment variables to react as well. During app deployment(in the build process) the environment variables must be replaced with the corresponding URLs (as this is the most frequently encountered use case in front-end applications). This can be done while configuring the build process.
Here is an example using Webpack https://medium.com/#trekinbami/using-environment-variables-in-react-6b0a99d83cf5
The whole idea here is to create a file (called just .env) filled with
your environment variables. To prevent people from finding out your
local database password is the same one you use for every single one
of your accounts on the internet , I urge you to add the .env file to
your .gitignore. Your front-end code will refer to the same
environment variable (process.env.API_URL) on both environments
(development/production), but because you defined different values in
your .env files, the compiled values will be different.
I would suggest having a separate .env file for the react app as it should not be accidentally served with the website.
Create React App has a module(built around the node dotenv module) you can use for adding custom environment variables
https://create-react-app.dev/docs/adding-custom-environment-variables/
The environment variables are embedded during the build time. Since
Create React App produces a static HTML/CSS/JS bundle, it can’t
possibly read them at runtime. To read them at runtime, you would need
to load HTML into memory on the server and replace placeholders in
runtime, as described here. Alternatively you can rebuild the app on
the server anytime you change them.
Its depend on how you are using react.
If you are using react-script, you can go will above solution(https://create-react-app.dev/docs/adding-custom-environment-variables/).
But if you are using webpack, try to use DotenvPlugin in place of dotenv module (https://webpack.js.org/plugins/environment-plugin/).
In my opinion, pls don't follow method 1 use in medium link, as env should not be push on git but package.json need to be done.

Integrate vue in a template with vars / props

I'm currently creating a vue app and wondering how to integrate it into a template and passing vars (props) into it.
So I basically run npm run dev, coding the app and all its components and so far everything is fine.
When I run npm run build I'll get some js in my build folder, created by webpack.
I guess (as seen before before here on stackoverflow) I can just load these files in my template, create an html-element mit the id "App" and everything works and the app initializes itself automatically.
But now my problem is: the app fires some Ajax requests, and depending on the environment the targets are different (dev: api.local, test: api.testsystem.com, prod: api.livesystem.com, ...).
And therefore I need to pass the url from outside into the app.
We don't build the app at deployment, as it's on a different repository than the "websites" using it. (Our plans are wether to copy the build files manually in these projects or offer an cdn-like url where the other projects load it). And with other projects I mean a symfony based website, or a typo3 plugin, ...
So, from React I remember you can initiate an app like React.render('app.js', {props: 'api-url': 'http://api.local'}); (don't kill me, it was somehow like this...)
How do I do it in vue?
Like:
new Vue(
<template>
<App :api-url="api-url" />
</template>
<script>
import App from "path/to/app.js";
export default {
data() {
api-url: "inject url here"
}
}
</script>
);
or add an data attribute like <div id="App" data-api-url="http://url"> and try to access it inside the app?
I've also seen something like an env-loader - but I'm not sure if this helps in my case.
You talk about different environment mode. You should read this documentation about how to start vue app with different env mode.
You can define different .env files for each mode and populate process.env with this file, or you can start vue.js with NODE_ENV=development per example, and check for process.env.NODE_ENV where you need to pass appropriate variables.

How to edit .env file after build completed reactjs

i had build react app web page
with custom environment variables
the problem is when i build the script
and change the .env variables no thing change in the website !
.env file :
REACT_APP_SITENAME=TheSiteName App
After building a react app all code is static and can't be changed. I think the only solution to send some dynamic data to your react app is to either create a special file per system you running your app on and load this directly inside the index.html or create the content of this file on the fly.
So when you're using create-react-app in public/index.html add something like this:
<head>
...
<script src="https://www.example.com/envconfig.js" type="text/javascript">
</script>
...
</head>
This file should contain the environmental config, e.g.:
window.globalConfig = {
siteName: "The Sitename App"
}
The file can also be created on the fly by PHP, Java or any other backend service. Just make sure to answer as valid Javascript.
And in your React app at index.js, App.js or anywhere you can access this variable as it is global:
const appConfig = window.globalConfig || { siteName: process.env.REACT_APP_SITENAME}
With this you've got an fallback to the static env config if globalConfig is not available, likely in development.
Now you can use appConfig in any way and provide it via redux, context or property to your components.
Last thing to mention, you have to make sure that the config-file is loaded before executing all the React code. So the file should be loaded before all the created React files.
Quote from the docs:
The environment variables are embedded during the build time.
It isn't possible to apply environment changes as runtime.
Reference
Here is an example of how to use the environment at runtime:
CodeSandbox
here is an idea:
add a json file (e.a. config.json) with your configuration to the "public" folder. That file will be in the root of the build:
{
"name": "value" }
in your React code, create a static class with the variable you want to configure:
class Config {
static name= "[default value overwritten by the config]"; }
somewhere high in the startup of your React application, read the json and set the static variable:
fetch("config.json") .then((r) => r.json()) .then((data) =>{
Config.name=data.name; })
now you can use that config anywhere you need it :
Config.name
Note that any configuration you make will be vulnerable for public eyes, since the file can be opened directly with a URL. Also note that when deleting that json file, everything will still work with the default value. You could implement some check that the file must exist.

Categories