Leveraging Vue.js's capabilities with an external setup file

Is it feasible for a Vue App to access an external configuration file? I envision a setup where I deploy the application along with the config file; then, I should be able to modify the configuration in the external file without needing to rebuild the entire application. Is there a way to accomplish this goal? Currently, I am utilizing a separate Vuex store, but changing the configuration necessitates rebuilding the entire app.

I neglected to specify that the project is built using Vue CLI.

Answer №1

Retrieve the config.json file from the public folder and then initialize your Vue application in the resolve callback.

Store your configuration keys in the /public/config.json file.

{
  "KEY": "value"
}

Next, navigate to your /src/main.js file.

fetch(process.env.BASE_URL + "config.json")
  .then((response) => response.json())
  .then((config) => {
       Vue.prototype.$config = config
       new Vue({
         router,
         store,
         render: (h) => h(App)
       }).$mount("#app")
  })

Your application will now have access to the loaded configuration globally. You can simply use

mounted() {
  this.$config.KEY // "value"
}

Update made on Nov 23, 2022 (Including Vue 3 Version):

// VUE 3 Version
const app = createApp(App)

fetch(process.env.BASE_URL + "config.json")
  .then((response) => response.json())
  .then((config) => {
    // either utilize window.config
    window.config = config
    // or apply [Vue Global Config][1]
    app.config.globalProperties.config = config
    // FINALLY, mount the app
    app.mount("#app")
  })

Answer №2

This is the method I used to achieve it:

Start by creating a config.js file in your public directory and set up the desired configurations:

window.VUE_APP_API_KEY = 'blahblahblah';

Next, include the following code snippet in the head section of your public/index.html file:

  <script type="text/javascript">
    var cachebuster = Math.round(new Date().getTime() / 1000);
    document.write('<scr' + 'ipt type="text/javascript" src="<%= BASE_URL %>config.js?cb=' + cachebuster + '"></scr' + 'ipt>');
  </script>

Now, within your VUE application, you can simply access the API key with window.VUE_APP_API_KEY. It's a straightforward and efficient method :)

Answer №3

Adapted from @Hammad's concept, this approach utilizes Vue.js 3 with TypeScript and the component API, integrating the app.provide() feature.

To set up your configuration keys, store them in a /public/config.json file.

{
  "KEY": "value"
}

In your /src/main.ts file:

fetch(import.meta.env.BASE_URL + 'config.json')
  .then((response) => response.json())
  .then((config) => {
    for (const key in config) {
      app.provide(key, config[key])
    }
    app.mount('#app')
  })

Subsequently, to access the configuration within components:

<script setup lang="ts">
import { inject } from 'vue'

...

const config_value = inject('KEY')

Answer №4

A route served by my node application is responsible for returning dynamically generated JS files and declaring a global object to store configuration details. This setup does not rely on Vue.

Within the index.html:

 <script type="text/javascript" src="config.js"></script>

In the node (server side):

  app.get('/config.js', (request, response) => {
    response.header('Content-Type', 'application/javascript');
    response.send(`MyConfig = ${JSON.stringify(config)}`);
  });

Usage in components (or any other location):

{
  data: () => ({
    someField: MyConfig.someField
  })
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

update the element that acts as the divider in a web address (Angular)

Is it possible to modify the separator character used when obtaining the URL parameters with route.queryParams.subscribe? Currently, Object.keys(params) separates the parameters using "&" as the separator. Is there a way to change this to use a differe ...

Run the .map() method at regular intervals of 'x' seconds

I have a certain function in mind: function fetchDesign (items) { items.map(item => item.classList.add('selected')) // additional code here } Is there a way to trigger item.classList.add('selected') every 2 seconds, while ensu ...

An issue arose when attempting to proxy to: localhost, at port 4200, for the API endpoint v1/generate

Currently, I am following a tutorial which guides me through the process of creating an application using Angular CLI, Node.js, and Express. A proxy is used to initiate the app, with the proxy configuration file looking like this: { "/api/*": { ...

Getting access to data properties within a v-template in Nativescript Vue

When I try to access my data like lowText inside the first Label element, it works fine. However, within the Pager component and the v-template, I lose access to it. How can I pass the context of it in this situation? <StackLayout> <Label :t ...

Issue encountered with Ionic and Angular 2: Denied application of style from 'http://localhost:8100/build/main.css' due to unsupported MIME type ('text/html')

Initially, everything was going smoothly with my Ionic build, but things took a turn when I tried to test it on my iPhone. After stopping the server and running ionic serve --address localhost, I noticed that my stylesheet wasn't loading. Even after r ...

Tips for resolving the warning message: "Utilize a callback function in the setState method to reference the

I'm having an issue with this code fragment as ESLint is giving me a warning: "Use callback in setState when referencing the previous state react/no-access-state-in-setstate". Can someone help me resolve this? const updatedSketch = await ImageManipula ...

Unlock the lightbox and send the user to the parent page

Is there a way to simultaneously launch a lightbox popup and redirect the parent page? I have an AJAX script that retrieves HTML content as a response. My goal is to display this content in a lightbox popup while also directing the parent window to a des ...

Transmitting a JavaScript file via a Node.js server

I have a NodeJS server that sends a JavaScript file to the client. However, the JavaScript file does not import the libraries it needs on the client side. I load these libraries on the client side before receiving the file. Why is the file unable to find t ...

A strategy for concealing the selected button within a class of buttons with Vanilla JS HTML and CSS

I have encountered a challenging situation where I am using JavaScript to render data from a data.json file into HTML. Everything seems to be functioning correctly, as the JSON data is being successfully rendered into HTML using a loop, resulting in multip ...

An async function cannot be used as a Constructor

I am in the process of creating a constructor function using JavaScript. This constructor needs to be asynchronous because I am utilizing the Phantom JS module for data scraping. As a result, an asynchronous function must be used to scrape data through Pha ...

I am constantly reminded by React hooks to include all dependencies

Imagine I am using useEffect to pre-fetch data upon initial rendering: function myComponent(props) { const { fetchSomething } = props; ... ... useEffect(() => { fetchSomething(); }, []); ... ... } My linter is warni ...

Seems like ngAfterViewInit isn't functioning properly, could it be an error on my end

After implementing my ngAfterViewInit function, I noticed that it is not behaving as expected. I have a hunch that something important may be missing in my code. ngOnInit() { this.dataService.getUsers().subscribe((users) => {this.users = users) ; ...

How to import a template from a different webpage in AngularJS

I have a situation where I need to include a template from one HTML page into another because they are both lengthy and it's not practical to keep them on the same page. Therefore, I have decided to separate them for better organization. Here is an ov ...

Flask and the steps to modify CORS header

While working on my localhost, I came across a CORS error when building an application to handle search queries for a different domain. The specific error was: "Cross Origin Request Blocked... (Reason: CORS header 'Access-Control-Allow-Origin' mi ...

Is there a way to track dynamic changes in window dimensions within Vue?

Working on my Vue mobile web app, I encountered an issue with hiding the footer when the soft keyboard appears. I've created a function to determine the window height-to-width ratio... showFooter(){ return h / w > 1.2 || h > 560; } ...and ...

Creating a visually appealing multi-bar chart in AngularJS: Tips for effectively presenting data

Imagine that I have the JSON data below: [ { month: "Jan", cost: 80, energy: 90 }, { month: "Feb", cost: 50, energy: 80 }, { month: ...

ng-view does not support ng-repeat rendering

I have a basic app using ng-view and ng-repeat. Initially, it worked fine without ng-view, but after switching to ng-view, the ng-repeat stopped functioning correctly. Oddly, when I clicked on the "menu" link, it displayed another set of $var instead of ch ...

Is there a way to modify the CSS display property upon clicking a link or button?

I have a ul with the id of "menu-list". The display property is set to "none" in my CSS file, but I want it to switch to "flex" when a link is clicked. I am trying to use the click event on the link to change the display prop ...

Is there a way for me to submit numerous requests to the Game Coordinator at once?

I am currently utilizing the node-globaloffensive library and I am facing an issue where my code is repeating itself and only returning one request back from the gc. My goal is to send multiple requests in order to receive every rank from all users in my d ...

Customize the label and value in Material UI React Autocomplete

If you visit this link, you can see an example of what I'm trying to achieve. My goal is to have the option label and value be different from each other. In the provided example, the following code snippet is used: const defaultProps = { ...