The purpose
When you run the following command in a Vite project to start the server, you can access it from your local PC via a browser, etc.
npm run devOutput:
➜ Local: http://localhost:5173/
➜ Network: use --host to expose
➜ press h + enter to show helpHowever, it cannot be accessed from other PCs.
This article introduces a procedure to enable access from other PCs, while retaining the npm run dev command for local testing.
Solution
Allow access from other PCs
First, we will try to allow access from other PCs.
Open package.json located at the root of your Vite project and find the following entry:
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},Modify this as follows:
I have added --host --port 5173 to the dev line. The number after Port is the port number of the server that will be created. It is recommended to specify it, as it can be cumbersome if it changes when accessing from other PCs.
"scripts": {
"dev": "vite --host --port 5173",
"build": "vite build",
"preview": "vite preview"
},Once the modifications are complete, execute the following command:
npm run devUnlike before the modification, an address is now displayed under “Network” as well, allowing access from other PCs. (It’s shown as X.X.X.X here, but an actual IP address will be displayed.)
➜ Local: http://localhost:5173/
➜ Network: http://X.X.X.X:5173/
➜ press h + enter to show helpDivide command
Although the method above allows access from other PCs, in most cases, you would first perform local testing before network testing.
Editing package.json every time you change the testing method is cumbersome (and prone to errors), so we will prepare a separate command.
Modify package.json as follows:
We are adding the devnet line.
Before:
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},After:
"scripts": {
"dev": "vite",
"devnet": "vite --host --port 5173",
"build": "vite build",
"preview": "vite preview"
},After the modification, if you run the following command, it will not be accessible from other PCs.
npm run devOutput:
➜ Local: http://localhost:5173/
➜ Network: use --host to expose
➜ press h + enter to show helpExecuting the following command allows access from other PCs.
npm run devnetOutput:
➜ Local: http://localhost:5173/
➜ Network: http://X.X.X.X:5173/
➜ press h + enter to show helpResult
I was able to prepare a method that allows access from other PCs while retaining the npm run dev command for local testing.


comment