vitejs / vite

Next generation frontend tooling. It's fast!
http://vitejs.dev
MIT License
67.07k stars 6.02k forks source link

SyntaxError: Identifier 'global' has already been declared while importing a json file with "global" key in SSR environment #17698

Closed korbinzhao closed 1 month ago

korbinzhao commented 1 month ago

Describe the bug

Error happened in a ssr vite react project while importing a json file as below:

index.tsx

import './test.json';

test.json

{
  "global": {
    "name": "全局"
  }
}

The error message is :

rror when evaluating SSR module /src/test.json:
|- SyntaxError: Identifier 'global' has already been declared
    at new AsyncFunction (<anonymous>)

Reproduction

https://github.com/korbinzhao/template-ssr-react-streaming-ts/blob/bug/ssr_json_global/src/App.tsx#L4

Steps to reproduce

No response

System Info

System:
    OS: macOS 13.5
    CPU: (8) arm64 Apple M1
    Memory: 173.59 MB / 16.00 GB
    Shell: 5.9 - /bin/zsh
  Binaries:
    Node: 20.11.1 - ~/.nvm/versions/node/v20.11.1/bin/node
    Yarn: 1.22.19 - ~/.yarn/bin/yarn
    npm: 10.2.4 - ~/.nvm/versions/node/v20.11.1/bin/npm
    pnpm: 8.14.1 - /opt/homebrew/bin/pnpm
  Browsers:
    Brave Browser: 102.1.39.111
    Chrome: 126.0.6478.127
    Edge: 114.0.1823.37
    Safari: 16.6

Used Package Manager

npm

Logs

No response

Validations

bluwy commented 1 month ago

The global is being shadowed from https://github.com/vitejs/vite/blob/e1fb0fa27097566c8fa5e792f965c29fc050b837/packages/vite/src/node/ssr/ssrModuleLoader.ts#L216

Internally Vite would generate code like this:

function (global, ...) {
    const global = "asd";
    Object.defineProperty(__vite_ssr_exports__, "global", { enumerable: true, configurable: true, get(){ return global }});
    __vite_ssr_exports__.default = {
        global: global
    };
}

Which causes the issue because global can't be re-declared. Perhaps Vite needs to rewrite the internal global declaration to avoid the error.

DemocracyAndScience commented 1 month ago

I have encountered the same problem, checking if there is' global 'in your i18n. It has been tormenting me all afternoon, and it is actually this problem