Skip to content

@cloudflare/vite-plugin doesn't tree shake node builtins #9609

Open
@hi-ogawa

Description

@hi-ogawa

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:

// We are in build mode so return the absolute path to the polyfill.
return this.resolve(result.resolved, importer, options);

// Mark this path as external to avoid messy unwanted resolve errors.
// It will fail at runtime but we will log warnings to the user.
return {
id: source,
external: true,
};

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 vitejs/rolldown-vite#248

Please provide any relevant error logs

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething that isn't workingvite-pluginRelating to the `@cloudflare/vite-plugin` package

    Type

    Projects

    Status

    Untriaged

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions