Cause
After using vite to build the project, you need to access the service debugging through the computer or mobile phone in the LAN. It is found that you can’t access it through the IP + port.
Problem recurrence
When you run the NPM run dev | serve
command, the following contents will be displayed.
> [email protected] 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
Cause of problem
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 is found that the service cannot be found because it is not exposed in the network.
resolvent
The console will display user -- host to expose
(use -- host
to expose the network)
usually, we will splice -- host
on the back of 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 to. If this is set to 0.0.0.0, it will listen to all addresses, including LAN and public network addresses.
So we found three solutions by consulting the documents:
1. Modify the vite. Config. JS
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()],
server: { // ← ← ← ← ← ←
host: '0.0.0.0' // ← new content ←
} // ← ← ← ← ← ←
}
2. Configure via vite cli
After executing the NPX vite -- host 0.0.0.0
command, you can use http://10.56.116.128:3000/
visited.
vite v2.3.7 dev server running at:
> Local: http://localhost:3000/
> Network: http://10.56.116.128:3000/
ready in 301ms.
3. Modify NPM script
Modify the script 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"
}
END