Vite and conditional dead code elimination

1.8k views Asked by At

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)?

1

There are 1 answers

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

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