React native and redux global environment variables - react-native

I am trying to find the best way to store environment variables such as API and CDN servers DNS.
I saw my other answers, most recommended on one of the following:
Store in global - Don't like it. Hate throwing stuff to global, much rather using proper scopes. Also, seems a bit of an anti-pattern, but if you disagree I'de love to hear your arguments.
Keep the environment data in a separate file, and load current environment from that file - won't work for me as those are dynamic variables that might change (switching to another environment, CDN changes etc.)
Pass it via props - I don't like the idea of passing the config down 7 components whenever I need the CDN to show an image.
Ideally, I would like to have an option to import a lib in different places in the app. Basically something like this:
# when app starts, somewhere in the master container
import envConfig from './envConfig'
# load config from API
API.loadconfig().than((data) => envConfig.setConfig(data))
Then, in other files
import envConfig from './envConfig'
const cdn = envConfig.cdn;
Does that make any sense? is there a better way to achieve the same goal?
How can I make an import module to have a state?

In my project, I had to pass down some global variables so that I can access them anywhere in my app. Here's how I achieved that-
Wrap your application inside a global component like App.
Render children inside that App like this-
<div>
{React.cloneElement(this.props.children, { ...this.props.globalState })}
</div>
If you're using Navigator in your app, you can pass global variables through the Navigator. Please refer to this file to see how to exactly implement that. It's 4 months old code, please forgive me for that.
Good luck!

Related

Can I use global variables in React Native to store user information?

I have an application that has hundreds of screens. I usually pass the variables from parent to child between the components with props. I find it very uncomfortable to pass the array with the user information hundreds of times.
I am testing the global variables of react native. Does it have any danger to use a global variable to save user information and modify it within the components?
I have searched for documentation and nothing is said. I know it's not correct in react, but it works wonders for me.
Any recommendation?
If that global variable is a constant or it's value doesn't effect rendering of components then you are good to use it as global variable or async storage.
But if it's value is changing and affecting the rendering of component then I highly recommend you to store that value as state and to make it global you can either use
1) Context api (https://reactjs.org/docs/context.html)
2) Or Redux

Nuxt - global components according to layout

I'm developing Nuxt universal application, where I have two layouts one for control panel and one for frond-end UI.
And the thing I need is to register global components, but I need them to be only global for specific layout, couse I dont want to download unnecesary scripts on my front-end app in its bundle.
Is there some way to do that?
According to docs global component's are registered on Vue prototype and will be accessible from any component within created Vue instance. That means, that as long you use single instance, all global registrations (components, filter, mixins, etc) will be shared.
So, the answer is that there is no easy way to do that, specially when Nuxt.js takes care of essential part of webpack configuration and route splitting.
Registering component's locally should be done, in order to optimize performance.
Another recommendation you might want to look at, is that even you optimize loading of components, application will still load all declared store modules, plugins, external libraries, etc. And the most important, from my experience, once automatic deployment has been setup for that application and some changes have to be deployed to control panel - whole site will have to go down for maintenance.
I would consider a good practice to separate front-end and control panel to their own apps, which keeps responsibility separated and is the only way to deliver best optimization to front-end part of application.
Control panel is usually available on a subdomain, but can be configured on the web server as a subfolder, e.g. domain.com/control-panel.
Two step can solve your problem:
make a global_component.js file into plugins directory
then add below code,
import Vue from 'vue'
import your_component from '../your component directory/your_component.vue'
Vue.component('your-component', your_component)
add this js file into Nuxt.config.js plugins block
plugins: ['#/plugins/global_component.js '],
now you can use your component into any template like below
<template>
<section class="container">
<your-component></your-component>
</section>
</template>

Dynamic publicPath When Rendering Pages with Vue SSR

We're happy users of Vue and its server-side rendering module, Vue SSR. One of the requirements of my project is that we be able to dynamically adjust Webpack's publicPath at runtime, so that we can obtain assets from our different CDNs (we have two, one for test and one for prod).
We are able to accomplish this easily on the client-side using the __webpack_public_path__ free variable, and you can also override the publicPath within the SSR client manifest for asset URLs injected into the <head>.
Yet we continue to have issues with asset URLs that are housed directly within our templates and are rendered by SSR. For example, imagine if we had the following image within our tag:
<img src="~#/test.png" />
Our goal is that, on both the server and the client, we could adjust that URL to be prefixed how we please via publicPath. There doesn't seem to be a way to dynamically update the publicPath once the vue-ssr-server-manifest.json has been generated, the resulting URL ends up being something relative like /static/test.png or whatever we original cited in our Webpack config.
Per our project constraints, it's not possible to rebuild our SSR bundle, so we need to do this at runtime. We've tried adding placeholder values as our publicPath, e.g. __CUSTOM_WEBPACK_PUBLIC_PATH__, and replacing them in the server bundle at runtime, but that ends up being ineffective since publicPath is also embedded in other Webpack generated files.
Wondering if there is a cleaner way to achieve what we need directly via Vue SSR, or if this is something we just can't configure at runtime. Thanks for reading!
Late follow-up here, but we eventually solved this issue.
We found that setting __webpack_public_path__ globally in our Node.js process did result in the correct public path being applied to our assets in our server bundle.
Once that global is present both on the window (e.g. client-side), and globally in the node process (e.g. server-side), things started working as we wanted.
We faced similar type of problems in our webapp as well. BTW, we implemented a CDN plugin for vue.
export const CDNPlugin = {
install(Vue, { CDN, assetsManifest }) {
Vue.prototype.$cdn = {
...CDN,
asset(name) {
return `${CDN.baseUrl}${assetsManifest[name]}`;
},
resource(filepath) {
return `${CDN.baseUrl}/resources/${filepath}`;
}
};
}
};
Install this plugin both of your ssr and csr file.
Vue.use(CDNPlugin, {
CDN: { baseUrl: 'https://my.static.cdn.com' },
assetsManifest: yourAssetManifestObject,
});
And the usage of this CDN plugin inside vue template is as below
<img :src="$cdn.asset('relative/path/to/asset/style.css')">
If you think it is helping a bit, then I can share more regarding our implementation.
I spent an entire day trying to figure this out. In the end I used this:
https://github.com/agoldis/webpack-require-from
Worked like a charm, client side and server. Be aware you need to set a global.MY_BASE_URL in your node/server somewhere AND you need to inject a window.MY_BASE_URL somewhere in your HTML. Then just configure webpack.
plugins.push(new WebpackRequireFrom({variableName: 'MY_BASE_URL'}));
Similar problem occurred in my project, and finally I worked it out.
Ryan's answer really helps, but there is one thing I want to clear up. __webpack_public_path__ is a LOCAL variable in webpack bundled code, which means __webpack_public_path__ and global.__webpack_public_path__ is not the same. You need to do something like
__webpack_public_path__ = process.env.ASSET_PATH;
to specify public path (https://webpack.js.org/guides/public-path/#on-the-fly FYI).
Last, please make sure your process.env.ASSET_PATH is not undefined, maybe you have to set it manually to global in your server code.
global.process.env.ASSET_PATH = process.env.ASSET_PATH;

How more correctly make Helper in VueJs?

I have some method to generate random hexademical color. It will be used in very few (3 or 5) parts of the project. So I want to separate it from main code into some kind of Helper or smth else, and include it when needed (not globally).
I have 2 working ways to do this:
Using mixins. What I don't like is that when you read the code, you can't separate your own methods from methods of mixin.
Using plugins. What I don't like with that is that you have to write import Vue from 'vue' + Vue.use(MyPlugin) every time in all files where you want to use it. After that, you can call it like this.$ColorHelper.getRandomHEX().
So, the question is about aesthetics visualization.
What is the best practices to do such things?
PS: project was created from template with webpack.
Our team decide use function import from files-helpers
For example:
import { getRandomColor, getBackgroundColor } from 'Global/helpers/colorHelper';
// .....
let color = getRandomColor();
What good:
Don't need use excess import + use as in plugins
Method visually stands out, what it not from this
What bad:
Cant see visually what the helper have method. But possible can fixed with aliases. We dont think yet
Vue plugins are global, you only have to call the Vue.use method once. Then they should work wherever you use that particular Vue instance.
In a default project setup you normally don't have multiple Vue instance so it should work globally.
From the docs:
Plugins usually add global-level functionality to Vue.
And:
Use plugins by calling the Vue.use() global method:
Vue.use(MyPlugin)
https://v2.vuejs.org/v2/guide/plugins.html

Dynamic component path in vuejs

I have a divided my vuejs application in to components and whenever i update the architecture of the application, I need to change the component path wherever added. This makes the application maintenance difficult. So I have added the component path to settings.json file and with that I am trying to load the component. But this is not working. Please see the code below.
import Registration from platform.urls.uiComponent+'Account/Registration'
Does any one have any idea how to set dynamic component path in vuejs ?
According to this answer it is not possible to do that. There is however an alternative way to achieve what you want to do if you use a tool such as webpack. In webpack configuration you can define an alias for a directory e.g. components, which you can use and afterwards change in a centralized location.