剧情介绍
最近写了一个Express + Vue前后端项目demo,打算部署到Heroku
部分目录结构如下
server.js // Express提供数据接口 package.json client/ // Vue前端显示数据 package.json
整个项目都保存到Github上,让Heroku自动部署
前端项目不能在本地打包,不然dist目录将会进入git,这样不太好
所以,部署的时候需要在线上完成打包操作
package.json如下
"scripts": { "postinstall": "npm run client-install && npm run client-build", "client": "npm start --prefix client", "client-build": "npm run build --prefix client", "client-install": "npm install --prefix client", "start": "node server.js", "server": "nodemon server.js --ignore client", "dev": "concurrently \"npm run server\" \"npm run client\"" },
client/package.json
"scripts": { "serve": "vue-cli-service serve", "build": "vue-cli-service build", "start": "npm run serve" },
Heroku会自动执行 : postinstall -> start
所以我在 postinstall 中对client前端项目进行了【依赖安装】和【项目打包】
上面的两个配置文件,在本地执行是没有问题的,
Heroku线上部署
到了Heroku线上部署报错了:
sh: 1: vue-cli-service: not found
截图:
网上的文章,大致说了3个解决方法
1、重新安装
将 文件夹node_modules 删除在执行 npm install 进行重新安装
2、指定路径
./node_modules/.bin/vue-cli-service build
3、全局安装
npm install @vue/cli-service -g
线下环境确实没问题,不过到了Heroku线上部署就无效
问题解决
进过多番百度,发现有类似文章提到了一个环境变量NODE_ENV=production
查看部署日志,果然发现了类似的设置,Heroku很热心的给我设置了环境变量
修改环境变量
{ "postinstall": "NODE_ENV=development && npm run client-install && npm run client-build && NODE_ENV=production" }
总算部署成功了
最后的package.json文件
"scripts": { "postinstall": "NODE_ENV=development && npm run client-install && npm run client-build && NODE_ENV=production", "client": "npm start --prefix client", "client-build": "npm run build --prefix client", "client-install": "npm install --prefix client", "start": "node server.js", "server": "nodemon server.js --ignore client", "dev": "concurrently \"npm run server\" \"npm run client\"" }
部署完后的地址
https://web-node-app.herokuapp.com/