转载https://blog.youkuaiyun.com/sinat_41087851/article/details/85762749
我们在利用vue脚手架(vue-cli)开发vue的项目时,在开发完毕是需要执行打包命令(npm run build)进行打包,打包后默认生成一个新的文件夹dist,项目的所有前端文件都在这个文件里面。这个时候如果我们需要以本地服务打开这个文件的时候,可以利用其它软件进行打开,比如phpstudy、xampp之类的软件开启本地服务端口(http://127.0.0.1或者http?/localhost:80)进行浏览已经打包完成的项目。
在这里,将介绍利用node中的express来打开本地端口进行浏览。
一、项目已经打包到项目根目录dist文件夹中;
二、直接在项目中进行下载express(npm i express -d);
三、直接在项目中进行下载中间件connect-history-api-fallback(npm i connect-history-api-fallback -d)
四、创建prod.server.js,内容如下:
//引入express
const express = require('express');
//引入中间件,解决history模式
const history = require('connect-history-api-fallback');
//监听的端口
const port = 9999;
const app = express();
//使用中间件
app.use(history());
//设置静态文件路径
app.use(express.static('./dist'));
//监听端口
module.exports = app.listen(port, function (err) {
if (err) {
console.log(err)
return
} else {
console.log('Listening at http://localhost:' + port + '\n')
}
})
五、在项目中执行 node prod.server.js,就可以在本地打开http://localhost:9999进行浏览项目