Vite: Replace env vars at build time

Viewed 693

I am using Vue + Vite + TS and I am building a few libraries that I would like to build and import somewhere else.

The point is that I set some environment variables using the dotenv, hence I can use things like import.meta.env.MY_VARIABLE.

But they are being availed during the run time of the place I run them, hence the env files need to be placed in the component that requires those libs.

I would like to know if there is way so they get replaced in the build time.

1 Answers

Maybe you want to use the define option.

let commonConfig =
{

  plugins: [vue()],

  resolve: {
    alias: {
      "@": fileURLToPath(new URL("./src", import.meta.url))     
    },
  },
  build: {
    rollupOptions: {
      input: {
        main: resolve(__dirname, 'index.html'),
        nested: resolve(__dirname, 'auth_redirect.html')
      }
    }
  }
}

export default defineConfig(({ command, mode, ssrBuild }) => {
  
  if (command === 'serve')
  {
//
    return commonConfig;

  } 
  else 
  {
    commonConfig.define = {
      "BUILD_TIMESTAMP": new Date().toISOString()
      
    };

    // command === 'build'
    return commonConfig;
  }
})

And then you can just assign BUILD_TIMESTAMP to any javascript variable in your appCode.

const buildNum = "BUILD_TIMESTAMP";//You will get right val in this.

define has to be compatible with https://esbuild.github.io/api/#non-analyzable-imports so gives issues in serve mode. So I have used it conditionally in build mode only. In Dev Mode you will see just raw value of buildNum variable.

Related