1 Star 0 Fork 119

niking/vue-cli 高级模板

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
static-server.js 2.53 KB
一键复制 编辑 原始数据 按行查看 历史
Sam-meng 提交于 2021-04-06 16:38 . docs
/**
* 静态资源服务 (node 运行)
* 通常用于预览/检查打包结果,或者临时给其他人员启用前端服务
*/
const express = require('express')
const compression = require('compression')
const { createProxyMiddleware } = require('http-proxy-middleware')
const { join } = require('path')
const os = require('os')
const open = require('open')
const BASE_URL = '' // 打包时的 process.env.BASE_URL
const port = 8181
const isHistoryMode = false
const projectDir = join(__dirname, './dist')
const app = express()
/* 代理,更详细的配置规则:https://github.com/chimurai/http-proxy-middleware#options */
app.use(
'/api',
createProxyMiddleware({
target: 'http://10.25.73.159:8081',
pathRewrite: { '^/api': '' },
}),
)
/* 静态资源 */
app.use(compression())
app.use(BASE_URL, function(req, res) {
let sendfilePath = req.path
let cacheControl = 'no-cache'
const isStatic = /\.\w+$/.test(req.path)
const isStaticHtmlEntry = isStatic && /^\/index\.html/.test(req.path)
const isStaticHashCache = isStatic && /^\/static-hash\//.test(req.path)
if (isStatic) {
if (isStaticHtmlEntry) {
cacheControl = 'no-store'
} else if (isStaticHashCache) {
cacheControl = 'public,max-age=31536000'
}
} else {
if (isHistoryMode) {
cacheControl = 'no-store'
sendfilePath = '/index.html'
} else {
if (req.path === '/') {
cacheControl = 'no-store'
}
sendfilePath = join(req.path, '/index.html')
}
}
res.setHeader('Cache-Control', cacheControl)
res.sendfile(
join(projectDir, sendfilePath),
err => err && res.status(err.status).send(err.status),
)
})
app.use((req, res) => res.status(404).send(404))
/* 启动 */
app.listen(port, function() {
const ip = (() => {
const interfaces = os.networkInterfaces()
for (const devName in interfaces) {
const iface = interfaces[devName]
for (let i = 0; i < iface.length; i++) {
const alias = iface[i]
if (
alias.family === 'IPv4' &&
alias.address !== '127.0.0.1' &&
!alias.internal
) {
return alias.address
}
}
}
})()
const local1 = `http://localhost:${port}${BASE_URL}`
const local2 = `http://127.0.0.1:${port}${BASE_URL}`
const network = `http://${ip || '未连接网络'}:${port}${BASE_URL}`
global.console.log('')
global.console.log(` Local1: ${local1}`)
global.console.log(` Local2: ${local2}`)
global.console.log(`Network: ${network}`)
global.console.log('')
open(ip ? network : local2)
})
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
JavaScript
1
https://gitee.com/niking/vue-cli-template.git
git@gitee.com:niking/vue-cli-template.git
niking
vue-cli-template
vue-cli 高级模板
master

搜索帮助

23e8dbc6 1850385 7e0993f3 1850385