Use configuration file to initialize a node_modules library - javascript

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

Related

How can I create environment variables and use them in a react library, without using webpack?

I have tried dotenv and cros-env. And also with mentioning it in this link
https://create-react-app.dev/docs/adding-custom-environment-variables/
However, it doesn't work for me
My .env file
MY_VAR=value
I have this in the file where I want to call it
console.log(process.env)
const { MY_VAR } = process.env
console.log(MY_VAR)
and i get this
As noted here, environment variables for your frontend must begin with REACT_APP. So try REACT_APP_MY_VAR and restart your React server afterwards.

Angular how to share the same setting of json configuration file for different environment

I have an Angular 9+ application that uses APP_INITILIZER to load the external json configuration file so that we can modify the file without rebuilding the app.
We have a few such configuration files for different environments like dev, qa, staging, etc. And in angular.json file, we specify which file to use in assets section.
We have some settings that are not related to environment. For example, the settings for colour
...
,
{
"title":"red",
"header":"blue"
},
...
The issue is each time we add new settings like above, we need to duplicate it in every config file. I wonder if there's a way to only add the common settings once, and reuse them in all other config files?
The approach I usually take is to have a common environment file like environment.common.ts but the file looks slightly different
export const commonEnv = {
title: 'red',
header: 'blue'
};
I then just merge the settings with the normal environment file using Object.assign.
import { commonEnv } from "./../environment.common";
import { environment } from './../environments/environment';
const mergedSettings = Object.assign(commonEnv, environment);
You can now use mergedSettings to get to all the settings.

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.

configurable vue frontend application

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();

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