1.問題描述:
npm run build
在dist 文件生成了 index 和 static 文件夾,為什么本地打開不了,給后端就能打開?
如何才能像訪問 npm run dev
的地址那樣訪問?
2.種簡單方法
2.1 修改配置在本地訪問
更改一些路徑參數(shù)后,然后再次運(yùn)行npm run build 就可以在本地打開index.html
改哪里?
config/index.js文件
build: { assetsPublicPath: '/' }
改成
build: { assetsPublicPath: './' }
修改后再次運(yùn)行 npm run build
雙擊 index.html 即可
2.2 通過在dist 目錄中起服務(wù)訪問
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請求的數(shù)據(jù)是通過訪問本地文件偽造的,那么會報(bào)跨域錯(cuò)誤
不支持跨域讀取本地data
本地訪問路徑如:
file:///Users/Downloads/vue-travel-master/dist/index.html
3.2 生產(chǎn)環(huán)境不支持proxyTable
config/index.js 中,只有開發(fā)環(huán)境dev中配置了proxyTable,支持訪問代理路徑
但是在 build 中配置無效,不支持代理地址
比如我在開發(fā)環(huán)境中請求數(shù)據(jù)
axios.get('/api/index.json?city=' + this.city)
開發(fā)環(huán)境的proxyTable:
proxyTable: { '/api': { target: 'http://localhost:8080', changeOrigin:true,//允許跨域 pathRewrite: { '^/api': '/static/mock' } }
訪問路徑會替換成 http://localhost:8080/static/mock/index.json
但是生產(chǎn)環(huán)境不支持這樣,路徑要寫全:
axios.get('/static/mock/index.json?city=' + this.city)
這樣在dist目錄下 node server 就可以訪問了和 npm run dev 的效果是一模一樣的!
起服務(wù)訪問地址:
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 提供了內(nèi)置的中間件 express.static 來設(shè)置靜態(tài)文件 app.use(express.static('./')); app.listen(port, hostname, () => { console.log(`Server running at http://${hostname}:${port}`); }); express.static('./')
express 會在靜態(tài)資源目錄下查找文件,即server.js的上層路徑dist目錄,現(xiàn)在你可以加載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 可運(yùn)行代碼鏈接
可下載運(yùn)行試試
總結(jié)
以上所述是小編給大家介紹的vue本地打開build后生成的dist文件夾index.html問題,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時(shí)回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
如果你覺得本文對你有幫助,歡迎轉(zhuǎn)載,煩請注明出處,謝謝!
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com