vue 配置history模式
目前很多項目都是基於hash模式路由,這種路由看起來不太美觀,而且微信授權、拼接參數等都需要特殊處理,最好是使用社區推薦的history模式,本文基於vue cli 3搭建的項目為例,記錄下如何配置單頁、多頁的history模式。
單頁的history模式
-
router.js
const router = new VueRouter({ mode: 'history', base: process.env.BASE_URL, routes })
-
vue.config.js
const projectName = process.env.BASE_URL module.exports = { publicPath: projectName, outputDir: path.resolve(__dirname, 'dist'), }
-
項目根目錄配置.env環境變量
BASE_URL=/your-path/
-
nginx配置
server { location ^~ /your-path { root html; # 根目錄 try_files $uri /your-path/index.html /index.html; } }
這里的try_files作用是按順序檢查文件是否存在,返回第一個找到的文件或文件夾(結尾加斜線表示為文件夾),如果所有的文件或文件夾都找不到,會進行一個內部重定向到最后一個參數,注意,最后一個參數回退的uri必須存在,不然會報內部500錯誤
多頁的history模式
多頁項目是放到域名的某個子目錄下面,所以都需要加一層base_url,
-
router.js
const router = new VueRouter({ mode: 'history', base: `${process.env.BASE_URL}module1`, // 這里直接把模塊路徑也拼接好 routes })
-
vue.config.js
const projectName = process.env.BASE_URL module.exports = { publicPath: projectName, outputDir: path.resolve(__dirname, 'dist'), pages: { module1: { // page 的入口 entry: 'src/pages/module1/main.js', // 模板來源 template: 'public/index.html', // 在 dist/index.html 的輸出 filename: 'module1.html', // 當使用 title 選項時, // template 中的 title 標簽需要是 <title><%= htmlWebpackPlugin.options.title %></title> title: 'module1', // 在這個頁面中包含的塊,默認情況下會包含 // 提取出來的通用 chunk 和 vendor chunk。 chunks: ['chunk-vendors', 'chunk-common', 'module1'] }, module2: { // page 的入口 entry: 'src/pages/module2/main.js', // 模板來源 template: 'public/index.html', // 在 dist/index.html 的輸出 filename: 'module2.html', // 當使用 title 選項時, // template 中的 title 標簽需要是 <title><%= htmlWebpackPlugin.options.title %></title> title: 'module2', // 在這個頁面中包含的塊,默認情況下會包含 // 提取出來的通用 chunk 和 vendor chunk。 chunks: ['chunk-vendors', 'chunk-common', 'module2'] } }, devServer: { historyApiFallback: { verbose: true, rewrites: [ // 本地開發需要配置,不然會訪問不到 { from: new RegExp(projectName + 'module1'), to: `${projectName}module1.html` }, { from: new RegExp(projectName + 'module2'), to: `${projectName}module2.html` } ] } } }
-
項目根目錄配置.env環境變量, 如果項目直接是放域名根目錄,直接寫個/即可
BASE_URL=/your-path/
-
nginx配置
location ^~ /your-path/module1 { root html; try_files $uri /your-path/module1.html /index.html; } location ^~ /your-path/module2 { root html; try_files $uri /your-path/module2.html /index.html; }
nginx匹配優先級
- 精確匹配 > 前綴匹配 > 正則匹配 > 正常匹配 > 全匹配