乐闻世界logo
搜索文章和话题

Vite https on localhost

1个答案

1

During development, using HTTPS helps simulate an environment closer to production and is useful for developing certain features that require a secure context, such as service workers, HTTP/2, etc. Vite, as a modern development tool, supports enabling HTTPS in local environments. Below are the specific steps and explanations:

Step 1: Generate SSL Certificate

First, generate an SSL certificate for your local server. You can use various tools to accomplish this task, such as mkcert, which is a straightforward option.

  1. Install mkcert
bash
# Install mkcert (on macOS) brew install mkcert # Install mkcert (on Windows, using Chocolatey) choco install mkcert
  1. Create a local certificate authority
bash
mkcert -install
  1. Generate a certificate for localhost
bash
mkcert localhost

This will generate two files: localhost.pem (certificate file) and localhost-key.pem (key file).

Step 2: Configure Vite

Next, configure HTTPS in your Vite project.

  1. Edit the Vite configuration file (e.g., vite.config.js) In the Vite configuration, provide a custom server option including HTTPS configuration.
js
import fs from 'fs'; import { defineConfig } from 'vite'; export default defineConfig({ server: { https: { key: fs.readFileSync('path/to/localhost-key.pem'), cert: fs.readFileSync('path/to/localhost.pem') } } });

Make sure to replace 'path/to/localhost-key.pem' and 'path/to/localhost.pem' with the actual paths where you store your certificate and key files.

Step 3: Start the Vite Project

Finally, start your Vite project as usual. If configured correctly, Vite will serve your application via https://localhost:3000 (or another configured port).

bash
npm run dev

or

bash
yarn dev

Summary

By following these steps, you can configure Vite to support HTTPS in your local development environment, which helps simulate production and safely test features requiring HTTPS. Using tools like mkcert simplifies certificate generation and management, making development more efficient and convenient.

2024年8月24日 23:50 回复

你的答案