Skip to content

a script tag referencing node_modules does not get browserHash injected causing double-instantiation #9828

@Rich-Harris

Description

@Rich-Harris

Describe the bug

I'm not sure if this is a bug or expected behaviour, but it's left me scratching my head and I'd love to know if there's a workaround at the very least.

When a module is imported via a project-relative URL (/node_modules/foo/index.js) and via a package name (foo), Vite resolves the latter to /node_modules/foo/index.js?v=xyz123, which causes the module to be instantiated twice. (In this example, optimizeDeps.exclude = ['foo'].)

This is causing headaches for SvelteKit users, as it causes failed instanceof checks. It doesn't happen when the package in question is installed outside the directory (e.g. in a workspace root), because in that case both references are resolved to /@fs/path/to/project/node_modules/foo/index.js.

Reproduction

https://github.com/Rich-Harris/vite-browserhash-repro

System Info

System:
    OS: macOS 12.5.1
    CPU: (10) arm64 Apple M1 Max
    Memory: 178.69 MB / 32.00 GB
    Shell: 5.8.1 - /bin/zsh
  Binaries:
    Node: 16.15.1 - ~/.nvm/versions/node/v16.15.1/bin/node
    Yarn: 1.22.19 - ~/.nvm/versions/node/v16.15.1/bin/yarn
    npm: 8.11.0 - ~/.nvm/versions/node/v16.15.1/bin/npm
  Browsers:
    Chrome: 104.0.5112.101
    Chrome Canary: 107.0.5258.0
    Firefox: 103.0.2
    Safari: 15.6.1
  npmPackages:
    vite: ^3.0.9 => 3.0.9

Used Package Manager

pnpm

Logs

No response

Validations

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions