6

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.

2 Answers 2

19

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, could you provide an example ? Here's what I tried to do : export function VueConfigs(){ return { $api_url : process.env.NODE_ENV === 'production' ? 'https://api.xxx.com' : 'https://yyy.test:8443', } }
This is fine, but sometimes you don't want to be putting tokens and things in SCM. Seems like we have a strategy where we use the .env.development or a .env.development.local (unsaved to git) and then Webpack is taking care of it. But this assumes you are building and deploying to a specific lab and those values are present either SCM or apart of some search and replace with CI/CD.
0

If you use Vite you can externalize a config file without a store with this:

Create your config js module for instance in config/settings.js

const config = {
    apiUrl:'https://yesno.wtf/api'
};

export { config }

Mark the file as external in vite.config.js

export default defineConfig({

.
.
.
  build: {
    rollupOptions: {
      external: ['/config/settings.js']
    }
  }
})

Access the file in your main.js and store the settings globally

import { config } from './config/settings.js'
app.config.globalProperties.config = config

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.