Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vite and conditional dead code elimination

I use Vite bundler and in my code I have the following function:

function doSomething() {
  if (!import.meta.env.VITE_SOMETHING) {
    return;
  }

  console.log("Hello");
}

I would expect that after building my app (npm run build) without defining VITE_SOMETHING env var I will see no Hello logging in the code, but I see it.

What is worse, on every place where I used import.meta.env.VITE_SOMETHING I see in the compiled output {BASE_URL:"/",MODE:"production",DEV:!1,PROD:!0}.VITE_SOMETHING. It does't looks very optimal.

Is it possible co configure Vite to optimize the output - remove unused code and duplications (which it introduced)?

like image 355
Martin Ždila Avatar asked May 31 '26 03:05

Martin Ždila


1 Answers

In current vite version it works as expected. This is example of correct configuration https://stackblitz.com/edit/vitejs-vite-cqttnd?file=tree-shaked/main.ts

like image 62
Александр Дубинин Avatar answered Jun 02 '26 19:06

Александр Дубинин