vue cli2.0路由的hash模式和history模式的打包並查看本地效果的方法

1,如果路由是hash狀態


首先打開項目文件夾。找到config文件夾裏的index.js文件中的build對象,將assetsPublicPath中的“ / ”,改爲“ ./ ”。

如圖
這裏寫圖片描述

然後進行打包

npm run build

如果的到如下提示,不會報任何異常或錯誤,
這裏寫圖片描述
如果想本地打開需要一個本地服務器,可以使用Hbuilder,或者安裝本地服務。

  • 首先確保是全局安裝。
npm install http-server -g
  • 根據目錄 cd 。
cd dist

這裏寫圖片描述

  • 輸入啓動命令。
http-server

這裏寫圖片描述

  • 瀏覽器輸入對應的鏈接。
http://127.0.0.1:8080

備註:如果沒有cd dist,直接在根目錄啓動服務的話瀏覽器需要輸入

http://127.0.0.1:8080/dist/index.html

2,如果路由是 mode:‘history’模式


使用此模式不需要在config文件夾裏的index.js文件中的修改build對象,assetsPublicPath中的“ / ”不變,也就是什麼也不要改動,直接打包。
此模式需要後端配合,詳情請看官網文檔,或者使用node進行配置app.js自己的服務。
代碼如下:

app.js

const http = require('http')
const fs = require('fs')
let server = http.createServer();

server.on('request', (req,res)=>{
	
	if(req.url.startsWith('/static')){
		
		fs.readFile('.' + req.url, (err,data) => {
			res.end(data);
		})
	} else {
		
		fs.readFile('./index.html', (err,data) => {
			res.end(data);
		})
		
	}
	
})

server.listen(8888);
console.log('Server running at http://127.0.0.1:8888/');

如圖把app.js放在dist文件下
這裏寫圖片描述

然後使用node命令啓動服務

node app.js

這裏寫圖片描述

最後打開瀏覽器輸入鏈接

http://127.0.0.1:8888

如果本文章對你有所幫助,請點個贊,謝謝!!!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章