workers-sdk
workers-sdk copied to clipboard
`@cloudflare/vite-plugin` doesn't tree shake node builtins
What versions & operating system are you using?
wrangler 4.20.0, @cloudflare/vite-plugin 1.6.0
Please provide a link to a minimal reproduction
https://github.com/hi-ogawa/reproductions/tree/main/cloudflare-vite-plugin-node-tree-shake
Describe the Bug
Given a following entry:
// src/entry.js
import crypto from "node:crypto";
export default {
fetch: () => {
if (false) {
console.log(crypto)
}
return new Response("ok");
}
}
When building with "compatibility_flags": ["nodejs_compat"], output includes
// dist/ssr/entry.js
const workerdCrypto = process.getBuiltinModule("node:crypto");
With "compatibility_flags": ["nodejs_compat"], output includes
// dist/ssr/entry.js
import "node:crypto";
This is likely because @cloudflare/vite-plugin resolves node builtin on its own but doesn't explicitly include a flag { moduleSideEffects: false } such as:
https://github.com/cloudflare/workers-sdk/blob/70ba9fbf905a9ba5fe158d0bc8d48f6bf31712a2/packages/vite-plugin-cloudflare/src/index.ts#L631-L632
https://github.com/cloudflare/workers-sdk/blob/70ba9fbf905a9ba5fe158d0bc8d48f6bf31712a2/packages/vite-plugin-cloudflare/src/index.ts#L837-L842
I'm not sure if this is intentional, but it probably makes sense to add moduleSideEffects: false as a general optimization of build. As a comparison, Vite SSR build does it so by deafult:
https://github.com/vitejs/vite/blob/feb3a11454d27706f39912a934cee8666f92a884/packages/vite/src/node/plugins/resolve.ts#L413
Also side note, some folks (and also myself) started to use @cloudflare/vite-plugin on rolldown-vite and got some issues due to rolldown internally injecting import "node:module" but not being tree-shaken. I think I'll raise a separate issue for future rolldown-vite compatibility but let me link the issue just in case you're interested https://github.com/vitejs/rolldown-vite/issues/248
Please provide any relevant error logs
No response