Vue打包后本地预览

3,319 阅读1分钟

Vue打包编译本地预览

前言

在Vue项目中,打包后会在dist下生成静态文件,直接打开就是空白页。

如果想查看打包后的效果,服务器一系列配置又太麻烦,那么我们可以自己启动一个服务来进行本地预览

本地预览

其实在 Vue-Cli 的官方文档中就给出了我们解决方案,使用一个 Node.js 静态文件服务器,例如 serve

Serve

# 安装
npm install serve -g
# 启动 (在打包后的dist目录下)
serve .

X8sR5n.png

运行成功后就能看到下预览的地址,但是这样还会出现一个问题,想要测试接口发现出现了跨域。那么就可以自行搭建一个Node服务来进行预览。

Node-serve

我们需要用到三个模块 expresshttp-proxy-middlewareconnect-history-api-fallback

express搭建本地服务器

http-proxy-middleware接口跨域的问题

connect-history-api-fallback处理Vue路由history模式,如果路由为默认hash模式则不需要这个模块

const path = require('path')
const express = require('express')
const history = require('connect-history-api-fallback')
const { createProxyMiddleware } = require('http-proxy-middleware');

const app = express()

// 处理单页应用路由
app.use(history())

// 代理对象地址
app.use('/api', createProxyMiddleware({
    target: 'http://webApi',
    changeOrigin: true,
    pathRewrite: {
        '^api': ''
    }
}));

// 加载静态资源
app.use(express.static(path.join(__dirname, './dist')))

// 启动服务
app.listen(3001, ()=> {
    console.log('success => http://localhost:3001')
})

End

这就是我目前本地的预览的方法,如果大家有更好的建议欢迎大家留言讨论