教你如何打包并用 http-server 本地预览
下面是针对 Vue CLI 和 Vite 两种常见脚手架,简洁、通俗的步骤说明,教你如何打包并用 http-server(或更合适的替代方案)本地预览。
一、共同前提(通用)
已安装 Node.js 和 npm/yarn。
项目根目录运行命令。
打包输出通常在 dist/ 目录(如果不同以你的配置为准)。
二、Vue CLI
打包:
npm run build
输出:dist/(可在 vue.config.js 里通过 publicPath 修改发布路径)
用 http-server 预览(简单快速):
npx http-server ./dist -p 8080
history 模式(Vue Router 的无 # 模式):
直接用 http-server 刷新非根路由会 404。解决方法:
临时预览推荐用 serve(支持 SPA fallback):
npx serve -s dist -l 8080或用小型 Express 服务(示例):
const express=require('express'),history=require('connect-history-api-fallback');
const app=express(); app.use(history()); app.use(express.static('dist')); app.listen(8080);生产环境请在 Nginx/Apache 上做 index.html 回退配置。
三、Vite
打包:
npm run build
输出:dist/(若项目在子路径部署,注意在 vite.config.js 里设置 base)
用 http-server 预览:
npx http-server ./dist -p 8080
history 模式注意事项:
同 Vue CLI,http-server 不会做 SPA fallback,推荐:
npx serve -s dist -l 8080
或使用上面给出的 express + connect-history-api-fallback 示例
四、常用小贴士(一句话)
快速预览用 npx http-server/dist;若需 SPA 路由回退直接用 npx serve -s dist;生产请用 Nginx/CDN。
若部署在子路径,记得设置 publicPath(Vue CLI)或 base(Vite)。
评论