详解如何将 Vue-cli 改造成支持多页面的 history 模(2)
2. 修改 build/dev-server.js 文件
主要修改文件中var app = express()到module.exports = app.listen(port, function (err) {之间的代码
var app = express()
var indexHTML
var adminHTML
// 引用前面创建的文件, 并将两个保存内容的函数传过去, 这里保存内容的变量写成对象或者数组也可以, 还可以少点代码
require('../config/setup-dev-server')(app, {
indexUpdated: index => {
indexHTML = index
},
adminUpdated: index => {
adminHTML = index
},
})
// 加载反向代理
Object.keys(proxyTable).forEach(function(context) {
var options = proxyTable[context]
if (typeof options === 'string') {
options = {
target: options
}
}
app.use(proxyMiddleware(context, options))
})
// 设置静态文件夹路由
var staticPath = path.posix.join(config.assetsPublicPath, config.assetsSubDirectory)
app.use(staticPath, express.static('./static'))
// 入口1路由
app.get(['/', '/category/:id'], (req, res) => {
res.send(indexHTML)
})
// 入口2路由
app.get(['/backend', '/backend/*'], (req, res) => {
res.send(adminHTML)
})
// 404 页面
app.get('*', (req, res) => {
res.send('HTTP STATUS: 404')
})
app.use(function(req, res, next) {
var err = new Error('Not Found')
err.status = 404
next(err)
})
app.use(function(err, req, res) {
res.status(err.status || 500)
res.send(err.message)
})
module.exports = app.listen(port, function(err) {
3. npm run dev 开始愉快的写代码吧
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持黑区网络。
