Create a command in Vite that can be accessed from outside the local machine.

この記事は約5分で読めます。
スポンサーリンク

Things I want to do

If you run the following command on a project created with Vite to start Server, you can access it from your local PC via a browser or other application.

npm run dev

output:

  ➜  Local:   http://localhost:5173/
  ➜  Network: use --host to expose
  ➜  press h + enter to show help

However, it cannot be accessed from other PCs.

This article describes how to maintain the `npm run dev` command for local testing while also providing access from other PCs.

スポンサーリンク

Solution

Allow access from other PCs

First, try allowing access from other PCs.

Open the package.json file in the root directory of the project you created with Vite and find the following entry.

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

Modify this section as follows:

The line `–host –port 5173` has been added to the `dev` line. The number after `port` is the port number of the server that will be created. It is recommended to specify this as it can be inconvenient if it changes when accessing from other PCs.

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

Once the corrections are complete, run the following command.

npm run dev

Unlike before the fix, the address is now displayed in the Network section, allowing access from other PCs. (Although it’s shown as XXXX, the actual IP address will be displayed.)

  ➜  Local:   http://localhost:5173/
  ➜  Network: http://X.X.X.X:5173/
  ➜  press h + enter to show help

Separate the commands

The above method allows access from other PCs, but in most cases, you’ll probably want to perform local testing first before moving on to network testing.

Editing package.json every time we change the testing method is tedious (and prone to errors), so we’ll prepare a separate command.

Modify package.json as follows:

Adding a line for devnet.

Before revision:

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

After correction:

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

After making the correction, running the following command will prevent access from other PCs.

npm run dev

output:

  ➜  Local:   http://localhost:5173/
  ➜  Network: use --host to expose
  ➜  press h + enter to show help

Executing the following command will allow access from other PCs.

npm run devnet

output:

  ➜  Local:   http://localhost:5173/
  ➜  Network: http://X.X.X.X:5173/
  ➜  press h + enter to show help
スポンサーリンク

Result

I was able to create a way to maintain the `npm run dev` command for local testing while also allowing access from other PCs.

コメント

タイトルとURLをコピーしました