基本思路
- 运行npm run deploy,一键npm install && node build/build.js && pm2 startOrRestart pm2.json
- build.js通过webpack将前端程序打包压缩成js放在dist中,并根据config/index.js中的配置填充了index.html
- pm2是node的守护进程,方便管理
- pm2 运行build/prod-server.js,开启express的web服务,api访问也能代理
- prod-server.js和dev-server.js类似,只是不需要热加载
几个重要的配置
var path = require('path')
var express = require('express')
var config = require('../config')
var proxyMiddleware = require('http-proxy-middleware')
var port = process.env.PORT || config.dev.port
var proxyTable = config.dev.proxyTable
var app = express()
app.use(require('connect-history-api-fallback')())
Object.keys(proxyTable).forEach(function (context) {
var options = proxyTable[context]
if (typeof options === 'string') {
options = { target: options }
}
app.use(proxyMiddleware(context, options))
})
app.use('/', express.static('./dist'))
if (process.env.NODE_ENV === 'production') {
process.on('uncaughtException', function (err) {
sentry.captureError(err);
});
}
module.exports = app.listen(port, function (err) {
if (err) {
console.log(err)
return
}
console.log('Listening at http://localhost:' + port + '\n')
})
- config/index.js 中配置好proxy
- pm2.json
{
"apps": [
{
"name": "project_name",
"script": "build/prod-server.js",
"instances": "max",
"log_date_format": "YYYY-MM-DD HH:mm Z",
"max_memory_restart": "500M",
"exec_mode": "cluster",
"env": {
"NODE_ENV": "production"
}
}
]
}
- 在package.json中添加scripts,一键发布
"deploy": "cnpm install && node build/build.js && pm2 startOrRestart pm2.json"
说明
- 如果需要上传到七牛,装一个插件,配置一下webpack即可
- 由于我这边是上传到qiniu的,没有实验本地dist的静态资源,如果有问题,再一起讨论
网友评论