本地预览静态站的几种方法

开发静态网站时,直接用浏览器打开 HTML 文件会遇到跨域限制、相对路径问题等困扰。搭建一个本地 HTTP 服务器是最简单的解决方案。

工具 功能特色 适用场景
Python http.server 系统自带,即开即用 快速预览,临时使用
http-server 配置丰富,跨域支持 开发调试,生产环境测试
live-server 热重载,自动刷新 开发阶段,实时预览

优势:部分系统自带,无需安装
局限:功能单一,配置有限

# Python 3
cd your-static-site-dir
python3 -m http.server

# Python 2 (已废弃)
python -m SimpleHTTPServer
# 指定端口
python3 -m http.server 8080

# 指定绑定地址(允许局域网访问)
python3 -m http.server 8080 --bind 0.0.0.0
# 创建临时服务器脚本
echo "import http.server; import socketserver; import os
os.chdir('path/to/your/site')
with socketserver.TCPServer(('', 8000), http.server.SimpleHTTPRequestHandler) as httpd:
    print('Server running at http://localhost:8000/')
    httpd.serve_forever()" > serve.py

python3 serve.py

http-server 是一个功能丰富的零配置静态文件服务器,生产级别的稳定性。

# 使用 npx(推荐,无需全局安装)
npx http-server [path] [options]

# 全局安装
npm install --global http-server
http-server
# 基础使用
http-server ./dist

# 指定端口
http-server -p 3000

# 自动打开浏览器
http-server -o

# 启用 CORS
http-server --cors

# 禁用缓存(开发时很有用)
http-server -c-1

# 组合使用
http-server ./build -p 8080 -o --cors -c-1
# 启用 HTTPS
http-server -S -C cert.pem -K key.pem

# 设置代理(处理 API 请求)
http-server -P http://localhost:3001

# 启用 gzip 压缩
http-server -g

# 自定义默认页面
http-server --default-ext html

特色功能:文件修改时自动刷新浏览器

# 全局安装
npm install -g live-server

# 使用
cd your-static-site-dir
live-server
# 指定端口
live-server --port=8080

# 指定入口文件
live-server --entry-file=./index.html

# 忽略特定文件
live-server --ignore=scss,my/templates

# 禁用浏览器自动打开
live-server --no-browser

# 启用 HTTPS
live-server --https=path/to/https.conf

创建 .live-server.json 配置文件:

{
  "port": 8080,
  "host": "localhost",
  "root": "./dist",
  "open": false,
  "ignore": "scss,my/templates",
  "file": "index.html",
  "wait": 1000,
  "mount": ["/components", "./node_modules"]("/components", "./node_modules"),
  "logLevel": 2,
  "middleware": ["./my-custom-middleware.js"]
}
# 允许局域网访问,分享给同事
python3 -m http.server 8000 --bind 0.0.0.0

# 查看本机 IP
ipconfig getifaddr en0  # macOS
ip route get 1 | awk '{print $7}' # Linux
# 绑定所有网络接口
http-server -a 0.0.0.0 -p 8080 -o

# 手机访问:http://你的电脑IP:8080
# 禁用缓存,启用 CORS
http-server ./build -c-1 --cors -S -C cert.pem
# 所有路由都返回 index.html
http-server ./dist --default-ext html --fallback /index.html

# live-server 自动支持
live-server --entry-file=./index.html
# 查看端口占用情况
lsof -i :8080  # macOS/Linux
netstat -ano | findstr :8080  # Windows

# 杀死进程
kill -9 PID
# 启用 CORS
http-server --cors

# 或在 Chrome 中禁用安全策略(仅开发使用)
open -n -a /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --args --user-data-dir="/tmp/chrome_dev_sess" --disable-web-security
  • 确保相对路径正确
  • 检查大小写敏感性
  • 使用 .htaccess 或服务器配置重写 URL
  • 临时预览:Python http.server,简单快捷
  • 开发调试:http-server,功能完善,性能优秀
  • 实时开发:live-server,修改即刷新,开发体验佳
  • 团队协作:http-server + 局域网共享,稳定可靠

推广:阿里云百炼大模型 9折优惠 + 所有模型各百万免费Token →