? 目前很多项目都是基于hash模式路由,这种路由看起来不太美观,而且微信授权、拼接参数等都需要特殊处理,最好是使用社区推荐的history模式,本文基于vue cli 3搭建的项目为例,记录下如何配置单页、多页的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错误
多页项目是放到域名的某个子目录下面,所以都需要加一层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;
}
原文:https://www.cnblogs.com/youthsnail/p/14404610.html