vue-router 啓用 history 模式下的開發及非根目錄部署

vue-router 的 history 模式是個提升顏值的好東西,沒有了 hash 的路由看起來清爽許多。html

開發的時候,若是咱們使用 devServer 來啓動服務,因爲通常不共用端口,咱們通常不存在非根目錄的問題。vue

而刷新後 404 的問題能夠藉助 historyApiFallback 來解決。 webpack

但當咱們項目對外開放時,每每沒法在域名根目錄下提供服務,這個時候資源的訪問路徑與開發時的根目錄就有了區別。nginx

首先,咱們經過 webpack 來配置一下項目中全部資源的基礎路徑,讓這份代碼在開發和生產環境中均可以正確找到資源。web

// config/index.js
module.exports = {
    dev: {
        ...
        // 開發環境根目錄 - 服務根目錄 - 絕對路徑
        assetsPublicPath: '/'
        ...
    },
    build: {
        ...
        // 生產環境根目錄 - 服務器訪問路徑 - 絕對路徑
        assetsPublicPath: '/test/project1/'
        ...
    }
}

// build/webpack.common.conf.js
const config = require('../config')
module.exports = {
    output: {
        publicPath: process.env.NODE_ENV === 'production'
            ? config.build.assetsPublicPath
            : config.dev.assetsPublicPath
    }
}

// build/webpack.dev.conf.js
const common = require('./webpack.common')
module.exports = merge(common, {
    devServer: {
        historyApiFallback: true
    }
}

而後在提供服務的服務器配置中作以下配置(以 nginx 爲例):vue-router

location /test/project1 {
        alias .../project1; // 項目的真實路徑
        index index.html;
        try_files $uri $uri/ /test/project1/index.html;
}

try_files 會按順序檢查參數中的資源是否存在,並返回第一個找到的資源,若是都沒有找到,它會讓 nginx 內部重定向到會後一個參數。服務器

對了,因此它的的做用是解決刷新 404 的問題。post

這裏值得注意的是 try_files 的參數是絕對路徑。ui

至此,你開啓 history 模式的項目就能夠順利的跑在任何路徑了。code

歡迎你們點評指正點個贊~ wink

原文連接 -《vue-router 啓用 history 模式下的開發及非根目錄部署》

相關文章
相關標籤/搜索