Home » vue » TypeScript + Vue: Loading static json configuration when opening index.html

TypeScript + Vue: Loading static json configuration when opening index.html

Posted by: admin November 26, 2021 Leave a comment

Questions:

I’m working on an app that requires an API key to be inserted into the config.

Since I’m using npm run build to generate a static page (dist folder with index.html that loads app.js and appropriate chunks and styles) – the config file gets read only once and then embedded into generated app.js.

Due to how it works, whenever I change values in the non-embedded config (available in the dist/public/ folder – the values don’t refresh in app.js as they should.

Is there any way to import config dynamically whenever index.html along with attached app.js reload?

Here’s what I tried:

import * as config from '../public/finnhub.config.json';

const stockProvider = reactive(new FinnhubStockProvider(config));

It does load the config – but only during the build, meaning it’s constant.

Answers:

Importing the config file would cause it to be bundled. If you want the config file to be read on demand instead, you could fetch it:

import { onMounted, ref } from 'vue'

export default {
  setup() {
    const config = ref({})

    const fetchData = async () => {
      const resp = await fetch('/finnhub.config.json')
      config.value = await resp.json()
    }

    onMounted(() => {
      fetchData()
    })
  }
}