Vite "Network use `--host` to expose"

created at 03-13-2022 views: 768

problem

After starting Vite, it prompts "Network use--hostto expose", and the service cannot be accessed through the network IP

cause

After building the project with Vite, when you need to access the service debugging through the computer or mobile phone in the local area network, it is found that it cannot be accessed through the IP + port.

problem is reproduced

When running the npm run dev | serve command, it will display the following content.

> vite-vue@0.0.0 serve /Users/UserName/Workspace/vue-vite
> vite | vite preview


  vite v2.3.7 build preview server running at:

  > Local: http://localhost:3000 | 5000/
  > Network: use `--host` to expose

problem causes

When another device in the LAN needs to access the service, it must be accessed through the local IP + port. After trying to access, it was found that the service could not be found because the service was not exposed to the network.

solution

user --host to expose will be displayed in the console (use --host to expose the network) Usually we will splicing --host after npm run dev | serve

After executing npm run dev | serve --host, the console will still display Netvork: user --host to expose

server.host

type: string

Default: '127.0.0.1'

Specifies which IP address the server should listen on. Setting this to 0.0.0.0 will listen on all addresses, including LAN and public addresses.

So by consulting the documentation, I found three solutions:

1. modify the configuration

Add the following to the vite.config.js file in the root directory

import vue from '@vitejs/plugin-vue'

/**
  * https://vitejs.dev/config/
  * @type {import('vite').UserConfig}
  */
export default {
   plugins: [vue()],

   // add this:
   server: { 
     host: '0.0.0.0'
   } 
}

2. configuration via Vite CLI

After executing the npx vite --host 0.0.0.0 command, it can be accessed through http://10.56.116.128:3000/.

  vite v2.3.7 dev server running at:

  > Local:    http://localhost:3000/
  > Network:  http://10.56.116.128:3000/

  ready in 301ms.

3. modify the npm script

Modify the scripts under the scripts node in the package.json file as follows:

"scripts": {
  "dev": "vite --host 0.0.0.0",
  "build": "vite build",
  "serve": "vite preview --host 0.0.0.0"
}
created at:03-13-2022
edited at: 06-01-2022: