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

1.问题描述:

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

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

2.种简单方法

2.1 修改配置在本地访问

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

改哪里? 
config/index.js文件

build: {
    assetsPublicPath: '/'
}

改为

build: {
    assetsPublicPath: './'
}

修改后再次运行 npm run build
双击 index.html 便可

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

step1:vue

在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:node

在dist 路径下,npm install express

step 3:ios

node server

3.其余:

3.1 本地访问不足

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

不支持跨域读取本地datagithub

本地访问路径如:ajax

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

3.2 生产环境不支持proxyTable

config/index.js 中,只有开发环境dev中配置了proxyTable,支持访问代理路径
可是在 build 中配置无效,不支持代理地址express

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

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 可运行代码连接

可下载运行试试

相关文章
相关标签/搜索