nuxt / nuxt

The Intuitive Vue Framework.
https://nuxt.com
MIT License
54.95k stars 5.03k forks source link

Nuxt3 vite hmr alway use protocal 'ws' #28396

Closed Alex-CZL closed 3 months ago

Alex-CZL commented 3 months ago

Environment

Reproduction

It's just a normal development environment. You can find it by directly starting with npm run dev

Describe the bug

image

When I was designing the front-end architecture, I hoped that a new project could be developed and debugged through localhost:3000, and could also be debugged through the https domain name through reverse proxy to localhost:3000. However, in the default scenario, vite hmr only initiates websocket requests of the ws protocol, which will cause the browser to block it for security reasons when I use https://example.com to access. So I need the hmr client to dynamically adjust the ws protocol according to the currently used http protocol. I tried many ways to solve this problem but failed, and finally used a more hacky method to solve it. If possible, I need an official recommended solution.

Additional context

No response

Logs

No response

Alex-CZL commented 3 months ago

The following is the hack I tried, but I don’t like this solution. If the official has any good suggestions, thank you very much.

use nuxt hooks: 'vite:extend'

image
if (typeof viteBuildContext.config.server!.hmr === 'object') {
    viteBuildContext.config.server!.hmr = {
      // !important 强制重写为非法值false,硬控vite hmr 自动根据运行时协议切换ws协议
      protocol: false as unknown as string,
    };
  }
wattanx commented 3 months ago

The following workarounds are available:

// nuxt.config.ts

export default defineNuxtConfig({
  hooks: {
    'vite:extend'({ config }) {
      if (config.server && config.server.hmr) {
        // @ts-ignore
        config.server.hmr.protocol = 'wss'
      }
    },
  },
})

This will be resolved in the next version of nuxi. https://github.com/nuxt/nuxt/issues/27558#issuecomment-2196259443

Alex-CZL commented 3 months ago

The following workarounds are available:

// nuxt.config.ts

export default defineNuxtConfig({
  hooks: {
    'vite:extend'({ config }) {
      if (config.server && config.server.hmr) {
        // @ts-ignore
        config.server.hmr.protocol = 'wss'
      }
    },
  },
})

This will be resolved in the next version of nuxi. #27558 (comment)

In fact, I know that this solution can solve the wss protocol problem. But what I want is to automatically adapt to the runtime protocol, that is, if you use http://localhost:3000 to access, then hot updates use the ws protocol; If you use https://example.com to access locally through a reverse proxy, then hot updates use the wss protocol; So from the current version, my method is relatively universal.

@manniL @wattanx