Vite 使用本地ip+localhost访问服务


默认配置

在vite.config.js中,如果未配置server.host,默认服务将以localhost进行启动,此时我们可以通过localhost:port或127.0.0.1:port进行应用访问

import { resolve } from 'path'
function pathResolve(dir: string): string {
  return resolve(process.cwd(), '.', dir)
}
export default defineConfig({
  resolve: {
    alias: {
      '@': pathResolve('src')
    }
  },
  server: {
    port: 8888,
    open: true
  },
  build: {
    assetsInlineLimit: 4096, // 小于此阈值的导入或引用资源将内联为 base64 编码,以避免额外的 http 请求。设置为 0 可以完全禁用此项
  }
})

终端控制面板

  > Local: http://localhost:8888/
  > Network: use `--host` to expose

IP配置

如果配置了server.host的值为0.0.0.0,静态资源服务将以localhost和本地Ip进行启动,此时我们可以通过localhost:port或127.0.0.1:port或localIp:port进行应用访问

import { resolve } from 'path'
function pathResolve(dir: string): string {
  return resolve(process.cwd(), '.', dir)
}
export default defineConfig({
  resolve: {
    alias: {
      '@': pathResolve('src')
    }
  },
  server: {
    host: '0.0.0.0'
    port: 8888,
    open: true
  },
  build: {
    assetsInlineLimit: 4096, // 小于此阈值的导入或引用资源将内联为 base64 编码,以避免额外的 http 请求。设置为 0 可以完全禁用此项
  }
})

以上增加的host配置,效果等同于在package.json中为vite命令增加参数 --host

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

终端控制面板

  > Network:  http://10.6.96.17:8888/
  > Local:    http://localhost:8888/


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM