Vue——项目部署到非根目录下的解决方案
問題描述
同一個生產部署項目,基內外網的訪問路徑并不相同,內網是基于域名根目錄來訪問,而外網卻指向了一個子目錄。
eg. :
vue-router: history模式
內網環境:192.168.1.1:8080/index.html
外網環境:domain.com/ttsd/index.html
由于開發出來的項目是要部署在客戶方,且客戶并不想單獨拿一個域名(或子域)來部署,這時,打包后的程序就要作一些配置方面的修改了。
解決方案
1、Vue配置
Vue 2
將 config/index.js 里的?assetsPublicPath: "/", 修改成?assetsPublicPath: "/app/",?
// PathsassetsRoot: path.resolve(__dirname, "../dist"),assetsSubDirectory: "static",assetsPublicPath: "/app/", //修改打包后路徑 修改這里Vue 3
在根目錄下新建 vue.config.js 文件,然后加上以下內容:(如果已經有此文件就直接修改)
module.exports = {publicPath: '', // 相對于 HTML 頁面(目錄相同) }2、修改路由
在路由的history模式下,所有的路由都是基于根路徑的,如 /xxxx ,由于部署目錄未知,所以我們可以根據 location.pathname 來獲取到當前訪問的文件路徑,來修改路由。
vue-router里提供了一個base的屬性
base類型: string 默認值: "/" 應用的基路徑。例如,如果整個單頁應用服務在 /app/ 下,然后 base 就應該設為 "/app/" 。
router => index.js
增加基礎路徑 base:"/app/"?
const router = new Router({mode: "history",// base: getAbsolutePath(),base: "/app/",routes: [...] ......動態獲取根路徑
function getAbsolutePath () {let path = location.pathnamereturn path.substring(0, path.lastIndexOf('/') + 1) }const routers = new Router({mode: 'history',base: getAbsolutePath(),... })參考文章
https://www.jb51.net/article/138942.htm
https://blog.csdn.net/weixin_34194551/article/details/92636219
https://www.cnblogs.com/mengyouyouyou/p/10912378.html
https://www.cnblogs.com/diantao/p/7776523.html
https://forum.vuejs.org/t/vue-cli-3-build-assets-public-path/35669
https://my.oschina.net/qingqingdego/blog/3006013
總結
以上是生活随笔為你收集整理的Vue——项目部署到非根目录下的解决方案的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java Web——ResponseBe
- 下一篇: Vue-CLI@4——html-webp