Vue3(history路由)+Vite2部署Nginx

401 阅读1分钟
  • vite配置

    打包后公共基础路径为'/',否则路径会报错

    base: process.env.NODE_ENV === 'development' ? '' : '/'
    
  • nginx配置:

    location / {
        root   html;
        index  index.html index.htm;
        # 使用history路由的关键配置
        try_files $uri $uri/ /index.html;
    }
    

    try_files

    语法规则: try_files file ... uri;try_files file ... =code;

    解析:

    1. 按指定的file顺序查找存在的文件,并使用第一个找到的文件进行请求处理
    2. 查找路径是按照给定的root或alias为根路径来查找的
    3. 如果给出的file都没有匹配到,则重新请求最后一个参数给定的uri,就是新的location匹配
    4. 如果是格式2,如果最后一个参数是 = 404 ,若给出的file都没有匹配到,则最后返回404的响应码
  • 前端动态路由:其他静态资源同理

    通过const modules = import.meta.glob('../views/**/*.vue')引入vue文件,modules['../views/temp/404.vue']获取

  • 前端请求(axios):

    const service = axios.create({
      baseURL: process.env.NODE_ENV !== 'development' ? import.meta.env.VITE_BASE_API : '', // 打包直接使用请求路径
      timeout: 30000,
    })
    
    service.interceptors.request.use(
      (config) => {
        if (config.url.substr(0, 1) !== '/') {
          // history路由前缀一定要加/ 否则会根据当前访问的url拼接请求路径
          config.url = '/' + config.url
        }
        if (process.env.NODE_ENV !== 'development') {
          // 打包去除/api或使用nginx配置
          config.url = config.url.substring(4)
        }
        // ...
        return config
      },
      (err) => {
        // ...
        return Promise.reject()
      },
    )