Thursday, 21 September 2023

Exclude node package from build step

I have my web app running on an edge environment where many of the node libraries are not supported.
I am using the PlanetScale connector which does support edge, but lately I needed to start storing database snapshots for safety reasons (disclaimer: no databases were harmed prior to this decision.....) + it's easier for quick CI.
To connect to my local db snapshot, I would normally use mysql2. But the problem is that the mysql2 package is not edge compatible and therefore it fails the build step.
Logically as I wouldn't want the edge environment have access to the mysql connector, I tried to inline import the connector like this:

...
let { CONNECTOR } = await import.meta.env
if (CONNECTOR === "mysql") {
   const mysql = await import("mysql2/promise");
}
...

Unfortunately this also did not work and failed the build step.
My last but very very very wrong approach was this abomination:

...
let { CONNECTOR } = await import.meta.env
if (CONNECTOR === "mysql") {
   const mysql = await eval(`import("mysql2/promise")`);
}
...

Though I haven't ever been so much ashamed about my code, this surprisingly works. It does pass the build step and also works fine when using it in my dev environment.

I have tinkered a little bit with the rollup and vite config to no avail. Is there any way I can achieve the same goal without this eval mess?

Note, that moving it as a dev dependency won't help either because Cloudflare does not pass the --production flag and it would probably throw an error at build time anyway



from Exclude node package from build step

No comments:

Post a Comment