QwikDev / qwik

Instant-loading web apps, without effort
https://qwik.dev
MIT License
20.83k stars 1.31k forks source link

[🐞] Variables only used by onRequest aren't removed on dev server, throws an error #3350

Closed DustinJSilk closed 1 year ago

DustinJSilk commented 1 year ago

Which component is affected?

Qwik Rollup / Vite plugin

Describe the bug

Qwik loads constant values in files even if they're only used by an onRequest. This causes an error in the browser.

For example a plugin@headers.ts file:

import { type RequestHandler } from "@builder.io/qwik-city";

const HEADERS: Record<string, string> = {
  "All-My-Headers": process.env.MY_VARIABLE!,
};

export const onRequest: RequestHandler = ({ headers }) => {
  for (const key in HEADERS) {
    headers.set(key, HEADERS[key]);
  }
};

process is not available in the browser and will throw an error. This is awkward to work around just for a dev environment. In preview and production this is not an issue.

This is probably quite similar to https://github.com/BuilderIO/qwik/issues/2759

Is there a way to run some automatic cleanup in the files before serving them?

Reproduction

https://github.com/DustinJSilk/qwik-issue-treeshaking/blob/main/src/routes/plugin%40headers.ts

Steps to reproduce

No response

System Info

N/A

Additional Information

No response

manucorporat commented 1 year ago

This is happening because we are not treeshaking in the dev server! it would be too costly.

I would recommend to instead, use the {env} from RequestEvent:

export const onRequest: RequestHandler = ({ headers, env }) => {
  env.get('MY_VARIABLE');
  for (const key in HEADERS) {
    headers.set(key, HEADERS[key]);
  }
};
DustinJSilk commented 1 year ago

Ok no problem, i'll close this ticket since its not something we can realistically solve without taking a hit on build times Thanks!