Vite服务器默认运行在127.0.0.1而不是localhost上。

12
每当我运行npm run dev时,默认情况下vite会在127.0.0.1域上运行。 如何让vite改为在localhost上运行? 以下是我的配置:

package.json:

  "scripts": {
    "dev": "vite --host=localhost",
    "build": "vite build",
    "preview": "vite preview"
  },

vite.config.js:

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react-swc'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
  server: {
    host: 'localhost',
    port: 3000
  }
})

vite console

3个回答

11

这是有意为之的。您可以查阅vite本地主机行为(请阅读注释)。 要禁用此行为,请按照那里解释的设置dns.setDefaultResultOrder('verbatim')或升级Node.js到17+。同时localhost

在您的vite.config中:

import { defineConfig } from 'vite'
import dns from 'dns'
import react from '@vitejs/plugin-react-swc'

dns.setDefaultResultOrder('verbatim')

export default defineConfig({
  plugins: [react()],
  server: {
    host: 'localhost',
    port: 3000
  }
})

结果:

vite console

希望这回答了你的问题!:)

6
另一种可行的解决方案是:

package.json:

 "scripts": {
    "dev": "vite --host",
    "build": "vite build",
    "preview": "vite preview"
  },

vite.config.js:

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react-swc'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
  server: {
    host: 'localhost',
    port: 3000
  }
})

结果:

vite console

阅读更多


1
刚刚面对了同样的问题,尝试使用dns.setDefaultResultOrder('verbatim')的解决方案,但遇到了TypeScript错误。
Property 'setDefaultResultOrder' does not exist on type 'typeof import("dns")'

这是因为我使用了Node 16,但安装了适用于Node 12的@types/node。只需更新类型包,一切都正常。
另外,我不需要设置port: 'localhost',只需使用setDefaultResultOrder即可。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接