vitejs / vite-plugin-react-swc

Speed up your Vite dev server with SWC
MIT License
823 stars 52 forks source link

Tries to execute `window.$RefreshReg$` during SSR #11

Closed thebuilder closed 1 year ago

thebuilder commented 1 year ago

Hey - This is cool addition to Vite. Trying the Vite 4 beta on a solution, where Vite is running through a middleware to do serverside rendering.

I have the following code, to inject the React preamble. For some reason, it seems like the plugin tries to instantiate it.

  if (import.meta.env.DEV && import.meta.env.MODE !== 'test') {
    /**
     * Inject the React Refresh runtime. This is required to get HMR working on dev
     * https://vitejs.dev/guide/backend-integration.html
     **/
    output.push(
      `<script type='module' src='${assetUrl}@vite/client'></script>`
    );
    output.push(`<script type='module'>
  import RefreshRuntime from "${assetUrl}@react-refresh"
  RefreshRuntime.injectIntoGlobalHook(window)
  window.$RefreshReg$ = () => {}
  window.$RefreshSig$ = () => (type) => type
  window.__vite_plugin_react_preamble_installed__ = true
</script>`);
  }

Results in me getting:

ReferenceError: window is not defined
    at eval (/src/entry-server.ts:6:3)
    at async instantiateModule (/node_modules/.pnpm/vite@4.0.0-beta.2/node_modules/vite/dist/node/chunks/dep-666774f5.js:53227:9)

Seems to be caused by this specific line (inside the template string):

  window.$RefreshReg$ = () => {}

If i remove that from the preamble, it renders correctly.

I've tried a few different scenarios, and it seems that the line being anywhere inside the code causes it to fail.

As a comment

// window.$RefreshReg$ = () => {}

As a string

'window.$RefreshReg$ = () => {}'

Without assignment

// window.$RefreshReg$

If change it to something else, like window.$RefreshRg$, the site renders.

ArnaudBarre commented 1 year ago

I will have a look later today, never tested the plugin in these conditions. Would be very helpful if you can spin up a stackblitz with your vite setup and a dummy component

thebuilder commented 1 year ago

Yeah I understand - I got a fairly complex setup, but I think it should be possible to replicate with a basic Vite middleware boilerplate example.

thebuilder commented 1 year ago

I tried setting up a StackBlitz container, but it fails to run after installing this package: https://stackblitz.com/edit/vitejs-vite-jj3dbh?file=package.json

Is there a known issue with StackBlitz and SWC?

Error: Bindings not found.
    at Compiler.eval (file:///home/projects/vitejs-vite-jj3dbh/node_modules/.pnpm/@swc+core@1.3.21/node_modules/@swc/core/index.js:225:19)
    at Generator.next (<anonymous>)
    at eval (file:///home/projects/vitejs-vite-jj3dbh/node_modules/.pnpm/@swc+core@1.3.21/node_modules/@swc/core/index.js:34:71)
ArnaudBarre commented 1 year ago

Oh yeah true that stackblitz doens't support swc for now. I will clone the repo and loot at it. Thanks