How to import a config file into Vue.JS+Vuex - vue.js

I'm setting configs in my main.js file before calling Vue :
Vue.prototype.$api_url = process.env.NODE_ENV === 'production' ? 'https://api.xxx.com' : 'https://yyy.test:8443'
It works if I access this.$api_url in any Vue file.
But in store.js (Vuex), it's another Vue Instance that is rendered, so I can't access this.$api_url.
What about setting the configs in a file and Vue.use(configs.js) ?
What should I do inside the configs file in order to get its variables in main.js/store.js ?
Thank you.

Make a standalone config.js file and export your config object from that file. And import config where ever you need config.
You can also assign the same config to Vue's prototype if you want that to be provided in all Vue components.
Update:
So here is how you can do this:
In your config.js
let config;
if (process.env.NODE_ENV === "production") {
config = {
$api_url: "https://api.xxx.com",
timeoutDuration: 30000,
someOtherProps: 'xyz'
};
} else {
config = {
$api_url: "https://yyy.test:8443",
timeoutDuration: 1000,
someOtherProps: 'abc'
};
}
export { config }
In your main.js
import { config } from 'config';
Vue.prototype.appConfig = config
use this.appConfig.$api_url whatever way you want to use in .vue files
In your store.js
import { config } from 'config';
use config.$api_url whatever way you want to use

Related

register dynamic components for vue app in seperate module file

I would like to make a js module file that imports vue component and register there.
and then inherit this component and use it for the app's main component.
I've found similar cases but the thing is, I don't use vue cli.
custom.js
import customMain from '/custom/components/main/main.js';
window.Vue.defineComponent('custom-main', customMain);
and in the app.js
import Main from '/global/components/main/main.js';
var App = createApp({
...
components: {
'global-main': Main,
},
template: `<component :is='mainComponent'></component>`,
computed: {
mainComponent() {
if(this.settings.customComponent){
return 'custom-main';
}else{
return 'global-main';
}
}
is this doable? what should I do to make this work?
is there other alternative way to load components dynamically?
The best approach for this case is defining a plugin named registerComponents in the plugins folder : plugins/registerComponents.js
import customMain from '/custom/components/main/main.js';
export default {
install: (app, options) => {
app.component('custom-main', customMain);
}
}
in App.js use the plugin:
import registerComponents from './plugins/registerComponents'
var App = createApp({....})
App.use(registerComponents)

Importing a Vue library in nuxt.js via plugins

Any idea how I'm going to use this plugin? https://github.com/DimanVorosh/vue-json-rpc-websocket/blob/e2199d89dc15f50e57e7c5c70adfd95e5ceb5cda/src/wsMain.js
I see that it is auto registering with vue but I can't use it in nuxt.
I created the plugins/vue-json-rpc-websocket.client.js, registered in nuxt.config.js as
'~/plugins/vue-json-rpc-websocket.client.js'
but I have no idea what to write in the inject method and IF I have to do it to make it work. this.$socket is undefined in component.
import Vue from 'vue'
import JRPCWS from 'vue-json-rpc-websocket'
Vue.use(JRPCWS, 'wss://bsc-ws-node.nariox.org:443', {
reconnectEnabled: true,
reconnectInterval: 5000,
reconnectAttempts: 3
})
// do I need this?
export default ({ app }, inject) => {
// Inject $hello(msg) in Vue, context and store.
// inject('hello', msg => console.log(`Hello ${msg}!`))
}
also, any idea how can I ENV the 'wss://bsc-ws-node.nariox.org:443' string?
Totally working on my side with the package that you're using and your given configuration. No need to inject anything so far!
Here is a fresh repo created for the example: https://github.com/kissu/so-nuxt-json-rpc-websocket
The below screenshot is using a console.log(this.$socket) in a mounted hook in /pages/index.vue but you can also use $vm0 and access the instance directly from the devtools after selecting the root component (in the screenshot too).
For the env variables part, you can create an .env file at the root of your directory like this
WS_URL="wss://echo.websocket.org"
// nuxt.config.js
export default {
publicRuntimeConfig: {
wsUrl: process.env.WS_URL,
},
}
Then, use this variable in your plugin like this
import Vue from 'vue'
import JRPCWS from 'vue-json-rpc-websocket'
export default ({ $config: { wsUrl } }) => {
Vue.use(JRPCWS, wsUrl, {
reconnectEnabled: true,
reconnectInterval: 5000,
reconnectAttempts: 3
})
}

React Native Expo Environment Variables

So I'm happy with the concept of environment variables as explained in this article and others
https://www.freecodecamp.org/news/how-to-gracefully-use-environment-variables-in-a-react-native-app/
Great, I've got my SOMETHING="something" stored so I can just use env.SOMETHING or whatever
The part I'm a little lost on is where you keep the live variables?
I would rather not do a solution like this as it seems you are still keeping your keys quite public and that you are just choosing based on the environment with if statements
Manage environment with expo react native
For example with an Express App deployment we have, we specify
let endPointURL = env.endPointURL
and then we keep a versoin of that variable locally and when it sits with AWS it is overridden by AWS servers as explained here
I was just wondering does something like that exist for Android and iOS builds (on the respective stores) or through Expo?
Thanks all
Honestly I think the way they go about it is a little silly. There may be a better way to go about than this, but I think I followed their documentation suggestions.
https://docs.expo.io/versions/latest/distribution/release-channels/#using-release-channels-for-environment-variable-configuration
They have a code snippet suggesting you create a function to look at the release configuration itself.
I interpreted it that you might do something like the code below and store your environment variables in a variables.js file and pull in your environment variables as such.
import Constants from 'expo-constants';
export const prodUrl = "https://someapp.herokuapp.com";
const ENV = {
dev: {
apiUrl: "http://localhost:3000"
},
staging: {
apiUrl: prodUrl
},
prod: {
apiUrl: prodUrl
}
};
function getEnvVars(env = "") {
if (env === null || env === undefined || env === "") return ENV.dev;
if (env.indexOf("dev") !== -1) return ENV.dev;
if (env.indexOf("staging") !== -1) return ENV.staging;
if (env.indexOf("prod") !== -1) return ENV.prod;
}
export default getEnvVars(Constants.manifest.releaseChannel);
Edit:
Now that Expo supports config file as app.config.js or app.config.ts, we can use the dotenv. Check this: https://docs.expo.io/guides/environment-variables/#using-a-dotenv-file
A simpler approach would be to export the env object instead of the function:
import Constants from 'expo-constants';
import { Platform } from "react-native";
const localhost =
Platform.OS === "ios" ? "localhost:8080" : "10.0.2.2:8080";
const ENV = {
dev: {
apiUrl: localhost,
amplitudeApiKey: null,
},
staging: {
apiUrl: "[your.staging.api.here]",
amplitudeApiKey: "[Enter your key here]",
// Add other keys you want here
},
prod: {
apiUrl: "[your.production.api.here]",
amplitudeApiKey: "[Enter your key here]",
// Add other keys you want here
}
};
const getEnvVars = (env = Constants.manifest.releaseChannel) => {
if (env === null || env === undefined || env === "" || env.indexOf("dev") !== -1) return ENV.dev;
if (env.indexOf("staging") !== -1) return ENV.staging;
if (env.indexOf("prod") !== -1) return ENV.prod;
}
const selectedENV = getEnvVars();
export default selectedENV;
// Import
import env from '..xxx/utility/env';
Get it in your ios-generated file, based on .env file:
In .env, write down GOOGLE_MAPS_API=abcde...
yarn add react-native-config
cd ios
pod install
In your Objective-C-compiled code, for example, AppDelegate.m:
#import "ReactNativeConfig.h"
NSString *mapsApiKey = [ReactNativeConfig envFor:#"GOOGLE_MAPS_API"];
[GMSServices provideAPIKey:mapsApiKey];
Credits to: ReactNative: Pass JS variable to AppDelegate based on https://github.com/luggit/react-native-config.
Android should work as well, but haven't tested / followed https://github.com/luggit/react-native-config.
Edit: required steps for Android:
<meta-data android:name="com.google.android.geo.API_KEY" android:value="#string/GOOGLE_MAPS_API"/> in AndroidManifest.xml.
In settings.gradle:
include ':react-native-config'
project(':react-native-config').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-config/android')
right after rootProject.name = 'XYZ'
In build.gradle:
apply from: project(':react-native-config').projectDir.getPath() + "/dotenv.gradle" right below import com.android.build.OutputFile and implementation project(':react-native-config') right below implementation "com.facebook.react:react-native:+" // From node_modules
Regarding "normal" usage in .ts, .tsx, .js files I'm declaring variables in .env based on https://github.com/goatandsheep/react-native-dotenv by declaring "module:react-native-dotenv" in babel.config.js in plugins, and it works like a charm like so:
import { ACCESS_TOKEN } from "#env";
...
headers: {
Authorization: `Bearer ${ACCESS_TOKEN}`,
Accept: "application/json",
},
Edit: important the eas build ignores .gitignore-declared variable, so if your .env is in .gitignore the production bundle won't have it included.
Surprised there weren't any answers that involved storing environment variables in a .env file with Expo.
I prefer storing my environment variables in a .env file because I don't want to commit certain variables to version control and hardwire them into my application code.
Create your .env file and add your environment variables
Install dotenv
npm install dotenv
In your app.config.js file, load the environment variables from the .env file via dotenv:
require("dotenv").config();
export default {
// config...
}
Expose the environment variables to the Expo runtime in the config in app.config.js:
require("dotenv").config();
export default {
// rest of config...
extra: {
ENV_VAR: process.env.ENV_VAR
}
}
Now you can access your environment variables through the following:
import Constants from "expo-constants";
const ENV_VAR = Constants.expoConfig.extra.ENV_VAR
OPTIONAL: TypeScript
To make using environment variables in our code a little nicer, lets create a typed helper utility to access the environment variables:
import Constants from "expo-constants";
export interface Env {
ENV_VAR: string;
}
/**
* Environment variables exposed through `app.config.js`
* An environment variable not there? Make sure it is explicitly defined in `app.config.js`
*/
export const env = Constants.expoConfig?.extra as Env;
Then you can simply access your environment variables from the env object:
const ENV_VAR = env.ENV_VAR
OPTIONAL: Throw an error if an environment variable is not set
This can be handy to prevent your app from running if an environment variable required for your app to properly function is not set.
In your app.config.js:
// Validate all necessary environment variables are set
const checkForEnvVariable = (envVar) => {
if (!process.env[envVar]) {
throw Error(`${envVar} not set! Check env.md for more information`);
}
};
[
"ENV_VAR",
// ...
].forEach((envVar) => checkForEnvVariable(envVar));

How to set root/base url for a laravel-vujs project?

I've deployed a VueJS project to a domain like www.example.com/demos/app,
But when I send a request to api from axios it is pointing to www.example.com/login instead of www.example.com/demos/app/login
Here is my request code using axios
export const login = ({ dispatch }, { payload, context }) => {
return axios.post('/login', payload).then((response) => {
// do something
}).catch((error) => {
// handle erros
})
}
One way you could go about this is to add a meta tag to the head of your page (like you may do with the csrf) and then reference it in your bootstrap.js file:
head
<meta name="api-base-url" content="{{ url('demos/app') }}" />
bootstrap.js (underneath window.axios = require('axios');)
window.axios.defaults.baseURL = document.head.querySelector('meta[name="api-base-url"]').content;
Hope this helps!
In config.js:
const CONFIG = {
API_URL_ROOT: 'http://localhost:8000/api/v1/',
}
export default CONFIG;
You can set axios default like this:
import config from '../config.js';
axios.create({
baseURL: config.API_BASE_URL
});
Or you can just set path by importing API_BASE_URL from config and then point it each time you make a get/post/put/delete call using axios
Laravel ships with axios and its imported in bootstrap.js, so simply go to bootstrap.js and add this:
window.axios.defaults.baseURL = 'http://example.test';
You can add this after window.axios.defaults.headers.common line
-Additional information:
axios.create will make an instance that has its own global url and configurations. use this if you have multiple urls or configuration and you want to use it in different components.
Create vue.config.js in Project root directory( if not exist ) -
In vue.config.js -
module.exports = {
publicPath: process.env.NODE_ENV === 'production'
? '/demos/app/'
: '/'
}
Then, Add the line in resources/js/bootstrap.js -
const {publicPath} = require("../../vue.config");
window.axios.defaults.baseURL = publicPath
.env
MIX_APP_URL="${APP_URL}"
resources/js/bootstrap.js
window.axios = require('axios');
window.axios.defaults.baseURL = process.env.MIX_APP_URL;
Update your APP_URL in .env file and add the above code on respective files.

React native require relative path file

I am trying React Native iOS and I was trying to setup project environments. I create a file called config.js so later I can just
import config from 'env'
to load the variables based on different environments. The following is the config.js file
let configFile = 'dev.js'
if (NODE_ENV === 'production') {
configFile = 'prod.js'
}
export default require('./env/' + configFile)
Somehow this won't work. the error message is:
Requiring unknown module "./env/dev.js". If you are sure the module is there, try restarting the packager or running "npm install"
When I changed my code to the following it would not give me errors. But it is not what I wanted to do.
export default require('./env/dev.js')
So does anyone know why is that?
Firstly, require calls are not dynamic. They are statically analyzed and bundled. So you would want something like this
let prodConfig = require('./env/prod.js');
let devConfig = require('./env/dev.js');
let config;
if (process.env.NODE_ENV === 'production') {
config = prodConfig;
}else {
config = devConfig;
}
export default config;