vite前端项目配置文件,解决打包一次,多服务器部署

背景

公司一个项目,会部署多台服务器,如演示环境、预生产、开发环境等等,总之环境个数很多,我们不能每次部署都 npm run build一次,我们需要抽出一个配置项,打包一次,交给运维,运维部署只需要修改配置项中的对应key即可

何为前端配置项

举个例子,比如系统的title、系统请求的根路径baseAPI、 文件服务器的根路径、地图服务路径、演示的模拟用户信息等,如下

js 复制代码
const defaultSettings = {
  minioBase: "http://baidu.com/minio/cestc-xingzhi-bucket", // minio路径
  baseApi: "/api", // 接口的base路径 开发为/api 生产可替换
  title:'测试的系统',
  defaultUser:'张三',
  mapUrl:'地图服务'
};

我们现在做的,就是将系统配置项抽离出来成单独文件,打包一次后,要运维修改对应配置,就可以部署多台服务器

以VITE为例,vue react均适用

首先我们在public 目录下,创建settings.js 并写入配置项 如上方defaultSettings,在index.html中引入 代码结构如下

代码中如何使用配置项

直接使用即可

如果使用ts报错,可根目录增加global.d.ts文件,并写好类型

如果此时ts仍然报错,查看tsconfig.json是否包含此类型文件

settings.js替换为生产配置

如果频繁部署某一个环境,开发环境使用settings.js配置,生产配置的配置项有区别,不能频繁修改打包好的setting.js,这是我们创建一个settings-prod.js,每次build的时候写一个脚本,将setting.js中的内容替换为settings-prod.js的,(当然这是一个实现思路,也可以ngnix配置,做代理,每次访问setting.js映射到服务器的系统配置路径)

现在public创建settings-prod.js,和根目录创建replace-settings.js,replace-settings.js为执行脚本,代码结构如下

replace-settings.js中代码脚本如下,作用是替换settings中的内容

js 复制代码
// replace-settings.ts
import { readFile, writeFile } from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const settingsProdPath = path.join(__dirname, "public", "settings-prod.js");
const settingsPath = path.join(__dirname, "public", "settings.js");

async function replaceSettings() {
  try {
    const data = await readFile(settingsProdPath, "utf8");
    await writeFile(settingsPath, data, "utf8");
    console.log("replaced");
  } catch (err) {
    console.error("no replaced", err);
  }
}

replaceSettings();

最后配置下package.json,每次build需要先替换文件内容,在打包

js 复制代码
"scripts": {
    "dev": "vite",
    "prebuild": "node replace-settings.js",
    "build": "npm run prebuild && vite build",
    "lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
    "preview": "vite preview",
    "preinstall": "npx only-allow pnpm"
  },
相关推荐
lyj16899717 分钟前
vue-i18n+vscode+vue 多语言使用
前端·vue.js·vscode
小白变怪兽2 小时前
一、react18+项目初始化(vite)
前端·react.js
ai小鬼头2 小时前
AIStarter如何快速部署Stable Diffusion?**新手也能轻松上手的AI绘图
前端·后端·github
墨菲安全3 小时前
NPM组件 betsson 等窃取主机敏感信息
前端·npm·node.js·软件供应链安全·主机信息窃取·npm组件投毒
GISer_Jing3 小时前
Monorepo+Pnpm+Turborepo
前端·javascript·ecmascript
天涯学馆3 小时前
前端开发也能用 WebAssembly?这些场景超实用!
前端·javascript·面试
我在北京coding4 小时前
TypeError: Cannot read properties of undefined (reading ‘queryComponents‘)
前端·javascript·vue.js
前端开发与ui设计的老司机4 小时前
UI前端与数字孪生结合实践探索:智慧物流的货物追踪与配送优化
前端·ui
全能打工人4 小时前
前端查询条件加密传输方案(SM2加解密)
前端·sm2前端加密