crm开发定制项目打包及部署到服务crm开发定制器二级路由
例如:crm开发定制我希望将打包的项目部署到 http://localhost:8088/web/ 上
一. 项目配置及打包
项目部署到服务器二级路由需要配置基础路径base,即需要:
1.配置vite.config.ts中的基础路径
2.配置路由的基础路径
方式一 通过环境变量配置基础路径
分别在production和development模式下的环境变量中添加基础路径变量,生产环境:.env.production文件,开发环境:.env.development文件
##生产环境NODE_ENV='production'VITE_BASE_PATH=/web/- 1
- 2
- 3
##开发环境NODE_ENV='development'VITE_BASE_PATH='/'- 1
- 2
- 3
vite.config.ts
在配置中添加:export default ({ mode }: ConfigEnv): UserConfig => { // 获取 .env 环境配置文件 const env = loadEnv(mode, process.cwd()); return { base: env.VITE_BASE_PATH, ... }}- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
router/index.ts
const router = createRouter({ history: createWebHistory(import.meta.env.VITE_BASE_PATH), routes})- 1
- 2
- 3
- 4
package.json
"scripts": { "dev": "vite serve --mode development", "build:prod": "vue-tsc --noEmit && vite build --mode production"}- 1
- 2
- 3
- 4
打包:
npm run build:prod- 1
方式二 通过打包时的指令配置基础路径
不用配置环境变量,vite.config.ts不用配置base属性,只需要在router/index.ts中添加:
const router = createRouter({ history: createWebHistory(import.meta.env.BASE_URL), routes})- 1
- 2
- 3
- 4
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",}- 1
- 2
- 3
- 4
- 5
- 6
打包:
npm run build:base --base /web/- 1
二. 配置及部署
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/; }}- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
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- 1
运行npm run demo时等同于vite build --mode production
运行npm run demo -- --base /web/时等同于vite build --mode production --base /web/
但是-- --有两个--,使用起来不太方便,于是改进一下指令:
demo: vite build --mode production --base- 1
运行npm run demo --base /web/时等同于vite build --mode production --base /web/