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"
  },
相关推荐
2401_837088501 小时前
ref 简单讲解
前端·javascript·vue.js
折果2 小时前
如何在vue项目中封装自己的全局message组件?一步教会你!
前端·面试
不死鸟.亚历山大.狼崽子2 小时前
Syntax Error: Error: PostCSS received undefined instead of CSS string
前端·css·postcss
汪子熙2 小时前
Vite 极速时代的构建范式
前端·javascript
叶常落2 小时前
[react] js容易混淆的两种导出方式2025-08-22
javascript
跟橙姐学代码2 小时前
一文读懂 Python 的 JSON 模块:从零到高手的进阶之路
前端·python
前端小巷子2 小时前
Vue3的渲染秘密:从同步批处理到异步微任务
前端·vue.js·面试
nightunderblackcat3 小时前
新手向:用FastAPI快速构建高性能Web服务
前端·fastapi
小码编匠3 小时前
物联网数据大屏开发效率翻倍:Vue + DataV + ECharts 的标准化模板库
前端·vue.js·echarts
欧阳天风4 小时前
分段渲染加载页面
前端·fcp