Skip to content

Vite rewrites this to globalThis in library ESM context #12340

@nex3

Description

@nex3

Describe the bug

I'm loading a file (call it library.js) through an ESM import, and compiling that import with Vite. Within library.js, Vite seems to be converting top-level references to this into globalThis. This is contrary to the definition of ESM modules, in which this is expected to be undefined. From MDN:

If the source is loaded as a module (for HTML, this means adding type="module" to the <script> tag), this is always undefined at the top level.

This is particularly troublesome because this === undefined is the most standard way to check whether the current context is being treated as ESM, which currently breaks in Vite.

Reproduction

https://stackblitz.com/edit/vitejs-vite-otqedk

Steps to reproduce

$ npm install
$ npx vite build
$ cat dist/vite-starter.js
console.log(`${globalThis} should be undefined}`);

System Info

System:
    OS: Linux 5.0 undefined
    CPU: (8) x64 Intel(R) Core(TM) i9-9880H CPU @ 2.30GHz
    Memory: 0 Bytes / 0 Bytes
    Shell: 1.0 - /bin/jsh
  Binaries:
    Node: 16.14.2 - /usr/local/bin/node
    Yarn: 1.22.19 - /usr/local/bin/yarn
    npm: 7.17.0 - /usr/local/bin/npm
  npmPackages:
    vite: ^4.2.0-beta.1 => 4.2.0-beta.1

Used Package Manager

npm

Logs

No response

Validations

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    Status

    Discussing

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions