Blog>
Snippets

Dynamic Configuration Loading in Vue with TanStack Config

Showcase how to dynamically load and apply different configurations based on the environment (development, production) in a Vue.js application using TanStack Config.
import { defineConfig, loadConfig } from 'tanstack-config-vue';

// Define a base config
const baseConfig = defineConfig({
  apiUrl: '',
  mode: ''
});
Defines a base configuration for the Vue.js application using `defineConfig` from TanStack Config. This base config will later be extended or overwritten based on the environment.
async function initConfig() {
  const env = import.meta.env.MODE;
  try {
    const envConfig = await loadConfig(import.meta.glob('./configs/*.json'), env);
    Object.assign(baseConfig, envConfig);
    baseConfig.mode = env;
  } catch (error) {
    console.error('Failed to load configuration:', error);
  }
}

initConfig();
Loads the environment-specific configuration asynchronously using `loadConfig` from TanStack Config. It uses dynamic imports with `import.meta.glob` to load all JSON files from a `configs` directory, then selects the appropriate config based on the `MODE` environment variable. The environment-specific config is merged into the `baseConfig`. Finally, it sets the application mode based on the current environment.
console.log(baseConfig.apiUrl); // Use the `apiUrl` from the loaded config
Demonstrates how to access the `apiUrl` property from the loaded configuration. This could be part of a Vue component or anywhere within the Vue app where the configuration needs to be accessed.