Skip to content

Externalized CJS imports in optimized dependencies don't return plain objects #19931

@jamesopstad

Description

@jamesopstad

Describe the bug

We are seeing some issues, such as cloudflare/workers-sdk#8907, where errors are preventing some optimized dependencies being used in development. In this particular case, mysql is erroring because its sub-dependency, safer-buffer requires buffer. buffer is excluded in optimizeDeps.exclude and the optimized mysql2.js includes:

// vite:cjs-external-facade:buffer
import * as m7 from "buffer";
var require_buffer = __commonJS({
  "vite:cjs-external-facade:buffer"(exports, module) {
    module.exports = m7;
  }
});

When this is used, it is assumed that the return value of require_buffer is a plain object with a hasOwnProperty method. As it is instead a module namespace object, this isn't the case and calling hasOwnProperty fails.

This could be resolved by changing module.exports = m; to module.exports = { ...m }; here:

`import * as m from ${JSON.stringify(
nonFacadePrefix + args.path,
)};` + `module.exports = m;`,

This works because spreading the object converts the module namespace object to a normal object. If this is the agreed solution then I'd be happy to open a PR. It would be good to first establish if there are any potential downsides.

Reproduction

https://github.com/jamesopstad/mysql2-repro

Steps to reproduce

Run pnpm i followed by pnpm dev.

System Info

System:
    OS: macOS 15.4
    CPU: (12) arm64 Apple M3 Pro
    Memory: 3.04 GB / 36.00 GB
    Shell: 5.9 - /bin/zsh
  Binaries:
    Node: 22.5.1 - ~/.nvm/versions/node/v22.5.1/bin/node
    Yarn: 1.22.22 - ~/.nvm/versions/node/v22.5.1/bin/yarn
    npm: 10.8.2 - ~/.nvm/versions/node/v22.5.1/bin/npm
    pnpm: 10.7.0 - ~/.nvm/versions/node/v22.5.1/bin/pnpm
  Browsers:
    Chrome: 135.0.7049.114
    Safari: 18.4
  npmPackages:
    vite: ^6.3.3 => 6.3.3

Used Package Manager

pnpm

Logs

TypeError: buffer.hasOwnProperty is not a function

Validations

Metadata

Metadata

Assignees

No one assigned

    Labels

    feat: deps optimizerEsbuild Dependencies Optimizationfeat: ssrp3-minor-bugAn edge case that only affects very specific usage (priority)

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions