vue本地打开build后生成的dist文件夹index.html问题

这篇文章主要介绍了vue本地打开build后生成的dist文件夹index.html问题,本文给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友参考下吧

1.问题描述:

npm run build 在dist 文件生成了 index 和 static 文件夹,为什么本地打开不了,给后端就能打开?

如何才能像访问 npm run dev 的地址那样访问?

2.种简单方法

2.1 修改配置在本地访问

更改一些路径参数后,然后再次运行npm run build 就可以在本地打开index.html

改哪里?

config/index.js文件

 build: { assetsPublicPath: '/' }

改成

 build: { assetsPublicPath: './' }

修改后再次运行 npm run build

双击 index.html 即可

2.2 通过在dist 目录中起服务访问

step1:

在dist 文件中添加 server.js

 var express = require('express'); var app = express(); const hostname = 'localhost'; const port = 8080; app.use(express.static('./')); app.listen(port, hostname, () => { console.log(`Server running at http://${hostname}:${port}`); });

step 2:

在dist 路径下,npm install express

step 3:

node server

3.其他:

3.1 本地访问不足

如果ajax请求的数据是通过访问本地文件伪造的,那么会报跨域错误

不支持跨域读取本地data

本地访问路径如:

file:///Users/Downloads/vue-travel-master/dist/index.html

3.2 生产环境不支持proxyTable

config/index.js 中,只有开发环境dev中配置了proxyTable,支持访问代理路径

但是在 build 中配置无效,不支持代理地址

比如我在开发环境中请求数据

axios.get('/api/index.json?city=' + this.city)

开发环境的proxyTable:

 proxyTable: { '/api': { target: 'http://localhost:8080', changeOrigin:true,//允许跨域 pathRewrite: { '^/api': '/static/mock' } }

访问路径会替换成  http://localhost:8080/static/mock/index.json

但是生产环境不支持这样,路径要写全: 

axios.get('/static/mock/index.json?city=' + this.city)

这样在dist目录下 node server 就可以访问了和 npm run dev 的效果是一模一样的!

起服务访问地址:

http://localhost:8080/static/js/app.5115f466b0f6ef56da51.js

3.3 express 配置

 var express = require('express'); var app = express(); const hostname = 'localhost'; const port = 8080;
 //Express 提供了内置的中间件 express.static 来设置静态文件 app.use(express.static('./')); app.listen(port, hostname, () => { console.log(`Server running at http://${hostname}:${port}`); }); express.static('./') 

express 会在静态资源目录下查找文件,即server.js的上层路径dist目录,现在你可以加载dist 目录下的文件了,如:

http://localhost :8080/static/mock/index.json?city=%E4%B8%8A%E6%B5%B7

访问路径为:

 ――dist ――static ――css ――js ――mock ――a.json ――index.html ――server.js

4. 代码

4.1 可运行代码链接

可下载运行试试

总结


如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

以上就是vue本地打开build后生成的dist文件夹index.html问题的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » Vue.js 教程