前面有一篇讲述了在heroku上部署接口api(https://blog.csdn.net/qq_40885461/article/details/89145746),部署Vue.js和这个有些许不同
我们通过使用 npm 来全局安装 heroku
npm install --global heroku安装成功后,我们使用以下命令查看版本号
heroku --version注册一个heroku账号
1.切换到项目目录,生成生产环境可用的代码,代码会生成在 dist 目录,我们只需上线该目录:
npm run build2.为了提交 dist 目录,需要删除 .gitignore 文件中忽略的 /dist/ :
.gitignore
.DS_Store node_modules/ # 注释 /dist/ 或者删除这一行 npm-debug.log* yarn-debug.log* yarn-error.log* # Editor directories and files .idea .vscode *.suo *.ntvs* *.njsproj *.sln3.在 dist 目录下新建 package.json 文件,添加项目信息和必要的依赖:
dist/package.json
{ "name": "longmusic", "version": "1.0.0", "description": "vue music", "author": "wenhui4001@gmail.com", "private": true, "scripts": { "postinstall": "npm install express" } }新建 package.json 文件的主要目的是,告诉Heroku 安装 express 框架来提供服务
4.在 dist 目录下新建 server.js 文件,使用express 框架创建服务:
dist/server.js
const express = require('express') const path = require('path') const serveStatic = require('serve-static') const app = express() const port = process.env.PORT || 5000 app.use(serveStatic(__dirname)) app.listen(port)5.登录你的Heroku账号
heroku login6.使用以下命令创建一个新应用
heroku create比如https://longmusic.herokuapp.com是应用的线上地址, https://git.heroku.com/longmusic.git是应用的仓库。
7.添加上面给出的远程仓库并检查:
git remote add heroku " https://git.heroku.com/longmusic.git" git remote -vps:如果还没有将代码加入版本控制,需要先切换到项目,进行Git初始化
git init8.部署上线,只需要提交 dist 目录就行
git add dist/ git commit -m "first commit" git subtree push --prefix dist heroku masterps:本地代码和线上的不一致时,可以强制推送:
git push heroku `git subtree split --prefix dist master`:master --force
打开线上应用:
heroku open