vue-cli3的二級域名使用history模式的各類問題學習

最近遇到須要配置二級域名的狀況,使用vue-cli三、router與nginx配置的時候,遇到了各類各樣的問題。在這裏記錄一下成功方法。

一、使用vue-cli建立一個新手項目。加上環境配置,補上vue.config.js配置

image
vue.config.js配置以下html

module.exports = {
    publicPath: process.env.VUE_APP_BASE_URL,
    outputDir: process.env.NODE_ENV === "production" ? "dist" : "dist-test",
}

package.json文件的scripts修改成以下,添加測試環境vue

"scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build --mode production",
    "testing": "vue-cli-service build --mode testing",
    "lint": "vue-cli-service lint"
  },

其中publicPath正式包是 '/' 而 測試包是 '/dist-test/'webpack

二、打開router文件,修改mode與base,base與publicPath同樣
const router = new VueRouter({
  mode: "history",
  base: process.env.VUE_APP_BASE_URL,
  routes,
})
三、啓動webpack打包,運行npm run testing與npm run build。項目根目錄生產dist與dist-test文件夾
四、配置nginx
server {
        listen       80;
        server_name  jun.wowqu.cn;

        location / {
            root   D:/learn/test-cli3/dist;
            try_files $uri $uri/ /index.html;
        }

        location /dist-test {
            root   D:/learn/test-cli3;
            try_files $uri $uri/ /index.html;
        }

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
五、運行nginx,訪問地址

image
image

六、結果不錯,主域名與子域名都沒問題。
七、總結

這裏的配置實際不難,最困難的是nginx的配置。官網給的例子實際很是模糊,根本沒有能讓人很好的處理二級域名部署。說明下最重要的nginx配置nginx

location /dist-test {
    #test-cli3是項目的根目錄,這裏的root不能是D:/learn/test-cli3/dist-test,假如帶上/dist-test會直接404。
    root   D:/learn/test-cli3;
    try_files $uri $uri/ /index.html;
}
八、補充

hosts添加了web

127.0.0.1 jun.cn
九、參考的大佬文章

vue-cli3 history模式下部署的各類坑

十、留下的疑問

怎麼才能使用在上面的publicPath與base使用'./'相對路由呢?不可能每次都寫死一個目錄吧?
畢竟在個人想法裏面,假如使用了'./'相對路由,那無論配置在哪一個項目域名下面,都不須要修改配置文件了。很方便。我看官網也有說這種方法的使用,惋惜我試了不能夠。
imagevue-cli

相關文章
相關標籤/搜索