如何配置Vite-React-TypeScript项目脚本以部署到Heroku?
解决Vite前端应用部署Heroku时缺少start脚本的问题
Heroku默认执行npm start启动应用,但当前项目的package.json中未配置该脚本,导致部署后启动失败,报错日志如下:
2022-08-23T23:34:35.000000+00:00 app[api]: Build succeeded 2022-08-23T23:34:35.042812+00:00 heroku[web.1]: Starting process with command `npm start` 2022-08-23T23:34:36.672295+00:00 app[web.1]: npm WARN config production Use `--omit=dev` instead. 2022-08-23T23:34:36.690924+00:00 app[web.1]: npm ERR! Missing script: "start" 2022-08-23T23:34:36.691004+00:00 app[web.1]: npm ERR! 2022-08-23T23:34:36.691142+00:00 app[web.1]: npm ERR! Did you mean one of these? 2022-08-23T23:34:36.691243+00:00 app[web.1]: npm ERR! npm star # Mark your favorite packages 2022-08-23T23:34:36.691273+00:00 app[web.1]: npm ERR! npm stars # View packages marked as favorites 2022-08-23T23:34:36.691308+00:00 app[web.1]: npm ERR! 2022-08-23T23:34:36.691345+00:00 app[web.1]: npm ERR! To see a list of scripts, run: 2022-08-23T23:34:36.691382+00:00 app[web.1]: npm ERR! npm run 2022-08-23T23:34:36.692657+00:00 app[web.1]: 2022-08-23T23:34:36.692823+00:00 app[web.1]: npm ERR! A complete log of this run can be found in: 2022-08-23T23:34:36.692964+00:00 app[web.1]: npm ERR! /app/.npm/_logs/2022-08-23T23_34_36_639Z-debug-0.log 2022-08-23T23:34:36.822926+00:00 heroku[web.1]: Process exited with status 1 2022-08-23T23:34:36.901286+00:00 heroku[web.1]: State changed from starting to crashed
当前项目的package.json配置:
{ "name": "JJ app", "private": true, "version": "0.0.0", "type": "module", "vite": "^3.0.7", "scripts": { "dev": "vite", "build": "tsc && vite build", "preview": "vite preview" }, "engines": { "node": "18.x" }, "dependencies": { "@fortawesome/fontawesome-free": "^6.1.2", "@types/axios": "^0.14.0", "axios": "^0.27.2", "eslint-config-react-typescript": "^1.0.10", "react": "^18.2.0", "react-dom": "^18.2.0", "react-router-dom": "^6.3.0", "w3-css": "^4.1.0" }, "devDependencies": { "@types/react": "^18.0.17", "@types/react-dom": "^18.0.6", "@vitejs/plugin-react": "^2.0.1", "typescript": "^4.6.4" } }
解决方案
方案一:使用Vite自带的preview命令(快速适配)
修改package.json中的scripts字段,添加start脚本,指定使用Heroku分配的端口:
"scripts": { "dev": "vite", "build": "tsc && vite build", "preview": "vite preview", "start": "vite preview --port $PORT" }
$PORT是Heroku动态分配的环境变量,必须使用这个端口才能让应用正常对外提供服务。
方案二:使用专业静态文件服务器(生产环境推荐)
Vite的preview命令主要用于开发阶段预览构建产物,生产环境更建议使用serve这类专门的静态文件服务器:
- 安装
serve依赖:
npm install serve --save
- 修改package.json中的
scripts字段:
"scripts": { "dev": "vite", "build": "tsc && vite build", "preview": "vite preview", "start": "serve dist -l $PORT" }
dist是Vite构建后的产物目录,-l $PORT指定监听Heroku分配的端口。
验证修改
修改完成后,重新提交代码到Heroku,Heroku会自动执行npm run build构建项目,然后通过npm start启动应用,即可解决启动失败的问题。
内容的提问来源于stack exchange,提问作者jsbrcad
相关产品推荐
相关产品推荐

