What is the best way to access data from a static config.json file in TypeScript within a Vue component following the execution of a build:electron command in Vue CLI 3?

Hey there!

I've been considering whether it's feasible to include a config.json file in a Vue CLI 3 project that can be dynamically read at runtime, both during development and production stages.

This config.json file will hold key strings that the application can utilize to alter content dynamically; for example, changing the video files shown to users or specifying the IP address of a printer.

// config.json

{
    "brand": "eat",
    "printerIP": "192.168.0.4"
}

I've made attempts to place the file within the assets folder as well as the public folder. I've experimented with importing it into the script lang="ts" part of App.vue using both import and require statements, while also making use of vue-property-decorator.

// App.vue (<script lang="ts">)

const config = require('../public/config.json');

OR

import config from '../public/config.json';

I have extracted the values by treating it like an API through axios, and alternatively simply accessed the variables by referencing them directly, such as config.brand.

// App.vue (<script lang="ts">)

import axios from 'axios';

@Provide() private brand: string = "";

axios
    .get('.config.json')
    .then(response => {
        this.brand = response.data.brand;
    })

OR

this.brand = config.brand;

Unfortunately, the data seems to only be accessible at build time and gets compiled into minified JavaScript. Consequently, if a user updates the variables in config.json after the app has been built, the changes won't reflect in the app unless the project is rebuilt. Ideally, I'm looking for a solution where I can modify a value in the build files via config.json and then have the app fetch the updated value at runtime without the need for rebuilding the entire project. Do you think achieving this is possible?

Your assistance on this matter would be truly appreciated.

Answer №1

It's important to store your runtime configurations in the public/ folder, but avoid importing them directly. When imported, webpack processes them during build time. Instead, utilize fetch for loading via HTTP.

In Vue, the public folder is where static assets go that should not be processed by webpack and are simply copied to dist/. To access these assets during runtime, use an HTTP request like this:

const getRuntimeConfig = async () => {
  const runtimeConfig = await fetch('/config');
  return await runtimeConfig.json()
}

If you need to use these configurations across multiple Vue components without repeating fetch calls, make a single fetch call in your main JavaScript file (e.g. src/main.js) and share the results using Vue mixins, as shown below:

Vue.mixin({
    data() {
        return {
          // Share runtime configs across Vue components
          BRAND: BRAND,
          PRINTER_IP: json.printerIP
        }
      },
    });

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

Remove objects from an array if they share identical key values

I'm having trouble getting this to work. I have an array of objects that looks like this: let myCities = [ { value: 'Barcelona', code: 02342837492482347 }, { value: 'Rome', code: 28282716171819 }, { v ...

Unable to locate the name 'JSON' in the typescript file

I have been working on an angular application where I have implemented JSON conversion functionalities such as JSON.stringify and JSON.parse. However, I encountered an error stating 'Cannot find name 'JSON''. Furthermore, there is anoth ...

The combination of Observable streams in combineLatest will persist even if one encounters a

I have a function designed to retrieve multiple documents from Firebase. fetchDocuments(documentIds: string[]): Observable<TreeNodeDocument[]> { const observables = []; for(let id of documentIds){ observables.push(this.fetchDocument( ...

What is causing my component to render the count value twice?

This is my main layout component: function MainPage() { return( <div> <MLayout children={<MNavbar custOrFalse={false} />} /> </div> ); } export default MainPage; Here is the child navbar compone ...

Utilizing AJAX and PHP POST to dynamically refresh innerHTML content with MySQL data updates

I've been trying to solve this problem for a long time now, and I've reached a point where I can't seem to figure it out. On a page, there are several forms where users input different information that gets submitted to a mySQL database usin ...

Aligning text vertically to the top with material UI and the TextField component

Seeking guidance on adjusting vertical alignment of text in <TextField /> const styles = theme => ({ height: { height: '20rem', }, }); class Foo extends React.component { ... <TextField InputProps={{ classes: ...

Why is my backend sending two Objects in the http response instead of just one?

When I receive data from my Django backend, sometimes instead of one object I get two objects within the HTTP response. This inconsistency is puzzling because it occurs intermittently - at times there's only one object, while other times there are two ...

Exporting numerous modules from an NPM package

Currently, I am working on a large Node and Typescript project called Project A. This project consists of numerous modules that I intend to reuse in another project, Project B. In order to achieve this reusability, I have configured the tsconfig.json file ...

Implementing real-time data updates on a webpage using Node.js

Currently, I am faced with the challenge of updating values on my page in real-time without the need for constant webpage refreshing. To illustrate, consider a scenario where a user filters a real estate website by location and receives results showing the ...

Function that activates traffic lights

Currently, I'm encountering errors while working on this project in Notepad. Can you help me figure out what's wrong with my code? I'm attempting to create an onload traffic light using an object array. The requirement is to implement this f ...

Leveraging icons with Bootstrap 4.5

I am currently exploring how to incorporate Bootstrap 4.5 icons using CSS. Do you have any examples of code that could guide me on how to achieve this? I am specifically interested in understanding the required CSS declarations that would allow me to use t ...

Filtering Dropdown List in AngularJS with a Text Input Field and a Submit Button for Filtering Option Values

After exploring , I discovered a feature that enables users to type in a text box and filter results in a pseudo-dropdown. My goal is to enhance this functionality or come up with a better approach for users to type and filter select box options, ultimate ...

Looking for assistance with navigating through this URL using Python (requests, beautifulsoup, or selenium) or Javascript (node js, puppeteer)?

While attempting to gather data, I encountered an interesting pagination challenge on the following URL: My expertise in Web Scraping was put to the test as this website implemented a unique JavaScript-driven pagination. For the initial 5 pages, it simply ...

Angular II slash avoiding Pipe

I am working on developing a customized pipe in Angular 2 that will handle the replacement of the backslash ('\') character in a given string. This backslash is commonly used to escape special characters. What I have accomplished so far: T ...

Utilizing AngularJS to invoke a particular function within a PHP script: A comprehensive guide

Utilizing AngularJS to interact with a PHP script, I am aiming to specifically call out individual functions. In the provided app.js script, the updatePost and deletePost functions are triggered by button clicks. While I've successfully separated the ...

Retrieve the child nodes from the array and organize them into a

Given an array of regions, where the highest region has key: 10 and parent_id: null, the goal is to restructure this array in order to return a tree representation. The desired regions tree structure for input [10] should be: Egypt Zone 1 Tagamo3 Giza H ...

Tips for converting JSON information on a website and inserting it into a designated division?

I've recently delved into front-end development, searching for solutions and hints without much success. I'm currently in the process of building my first website, specifically a "find recipes" website. Lacking knowledge of API calls, I created a ...

Creating robust unit tests for Node.js applications with the help of redis-mock

I am facing an issue while trying to establish a connection with redis and save the data in redis using the redis-mock library in node-typescript, resulting in my test failing. Below is the code snippet for the redis connection: let client: RedisClientTyp ...

Setting up Babel to effectively function across multiple directories

I've been utilizing Babel for some time now and it effectively transforms my ES Next code to the dist directory using this command: babel src --out-dir dist --source-maps --copy-files Up until now, all my JavaScript code has been stored in the src fo ...

Long Polling results in the call stack size being exceeded to the maximum limit

I am working on a long polling function that needs to be triggered at a specific time, and then continue as long as the gallery has the updating class. The gallery is represented by $("... "). function pollGallery(gallery){ if (gallery.hasClass("upda ...