vue.jsenvironment-variablesvitequasar-frameworkquasar

Dynamic Alias Configuration in Quasar/Vite's extendViteConf Fails with Environment Variables


I'm working on a Quasar (v2) project using Vite (quasar cli) as the build tool, and I need to deploy multiple instances of nearly the same web application, each with different assets, images mostly. For example, instance "ins1" should use assets from src/assets/ins1, while instance "ins2" should use src/assets/ins2. My goal is to use a dynamic alias for assets so that components can reference assets consistently (e.g., <img src="~assets/background.svg">) while the alias points to the appropriate folder based on a configuration.

I planned to redefine the assets alias in quasar.config.js using extendViteConf, with the folder determined by an environment variable (VITE_ASSET_ROOT) from a .env file ( I also defined it in the build.env config just in case). For example:

// quasar.config.js
build: {
  env: {
    VITE_ASSET_ROOT: process.env.VITE_ASSET_ROOT || 'default',
  },
  extendViteConf(viteConf) {
    console.log('VITE_ASSET_ROOT:', process.env.VITE_ASSET_ROOT); // Still undefined
    viteConf.resolve.alias['assets'] = path.resolve(__dirname, `src/assets/${process.env.VITE_ASSET_ROOT || 'default'}`);
  },
}

And in the root folder:

//.env
VITE_ASSET_ROOT=ins1

The environment variable VITE_ASSET_ROOT is undefined in extendViteConf, so the alias falls back to src/assets/default. However, VITE_ASSET_ROOT is correctly available in components via import.meta.env.VITE_ASSET_ROOT. Setting VITE_ASSET_ROOT in the terminal (e.g., export VITE_ASSET_ROOT=ins1) works, but I want to use .env for local development. Attempt with build.env: Based on Quasar's documentation, I tried defining the variable in build.env to make it available in both client and server contexts:

This didn't work; process.env.VITE_ASSET_ROOT remains undefined in extendViteConf. I also tried using beforeDev to set process.env, but it runs too late to affect extendViteConf. Workaround: I can load .env manually with dotenv or use a static config.js file, but I want to understand why the native approach fails.


Solution

  • In my case, it was a bug in the older versions I was using quasar=2.14.2", with quasar/app-vite=1.7.1".
    I upgraded those packages and it worked.