项目打包及部署到服务器二级路由

例如:我希望将打包的项目部署到 http://localhost:8088/web/ 上

一. 项目配置及打包

项目部署到服务器二级路由需要配置基础路径base,即需要:
1.配置vite.config.ts中的基础路径
2.配置路由的基础路径

方式一 通过环境变量配置基础路径

分别在productiondevelopment模式下的环境变量中添加基础路径变量,生产环境:.env.production文件,开发环境:.env.development文件

##生产环境
NODE_ENV='production'
VITE_BASE_PATH=/web/
##开发环境
NODE_ENV='development'
VITE_BASE_PATH='/'

vite.config.ts

在配置中添加:
export default ({ mode }: ConfigEnv): UserConfig => {
  // 获取 .env 环境配置文件
  const env = loadEnv(mode, process.cwd());
  return {
    base: env.VITE_BASE_PATH,
    ...
  }
}

router/index.ts

const router = createRouter({
  history: createWebHistory(import.meta.env.VITE_BASE_PATH),
  routes
})

package.json

"scripts": {
  "dev": "vite serve --mode development",
  "build:prod": "vue-tsc --noEmit && vite build --mode production"
}

打包:

npm run build:prod

方式二 通过打包时的指令配置基础路径

不用配置环境变量,vite.config.ts不用配置base属性,只需要在router/index.ts中添加:

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})

import.meta.env.BASE_URL为vite内置
package.json

"scripts": {
  "dev": "vite serve --mode development",
  "dev:base": "vite serve --mode development --base",
  "build:prod": "vue-tsc --noEmit && vite build --mode production"
  "build:base": "vue-tsc --noEmit && vite build --mode production --base",
}

打包:

npm run build:base --base /web/

二. nginx配置及部署

server {
  listen       8088;
  server_name  localhost;
  location /web {
    #二级路由时需要使用别名alias,不用root
    alias html/dist/;
    index  index.html;
    #若不配置try_files,刷新会404
    try_files $uri $uri/ /web/index.html;
  }
  #后台接口
  location /prod-api/ {
    proxy_pass http://172.16.20.30:9905/;
  }
}

Vite基础路径指令配置原理

在vite当中,官方提供了一些内置环境变量,其中就包括BASE_URL,该值默认为/,在项目文件中,必须通过import.meta.env.xxx的方式调用环境变量,此处为import.meta.env.BASE_URL,之后,vite会将import.meta.env.BASE_URL替换为内置的BASE_URL的值,并可以通过指令:--base <path>设置BASE_URL的值

使用npm运行脚本时可以传递参数,在package.json中添加指令:

demo: vite build --mode production

运行npm run demo时等同于vite build --mode production
运行npm run demo -- --base /web/时等同于vite build --mode production --base /web/
但是-- --有两个--,使用起来不太方便,于是改进一下指令:

demo: vite build --mode production --base

运行npm run demo --base /web/时等同于vite build --mode production --base /web/

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。