怎么实现vue本地打开build后生成dist文件夹index.html

这篇“怎么实现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

以上就是关于“怎么实现vue本地打开build后生成dist文件夹index.html”这篇文章的内容,相信大家都有了一定的了解,希望小编分享的内容对大家有帮助,若想了解更多相关的知识内容,请关注蜗牛博客行业资讯频道。

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:niceseo99@gmail.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

评论

有免费节点资源,我们会通知你!加入纸飞机订阅群

×
天气预报查看日历分享网页手机扫码留言评论电报频道链接