1) 背景:
我们项目是2个前端3个后端的配置。前端和每个后端都有需要调试的接口。
因此经常切换vite.congig.js中的proxy后端代理链接,是挺麻烦的。
| 于是我研究如何能快速切换后端URL,所幸懒人有懒福,我找到了Inquirer 和 fs, |
| 实现执行 npm start 可直接切换vite.config.js中proxy的代理URL,然后直接启动项目。 |
复制

2) inquirer 和 fs npm包
| 先来说说Inquirer ,Inquirer是一个流行的 Node.js 库,用于构建交互式命令行界面。 |
| fs是用于读取,写入,修改文件的工具。 |
复制
简单介绍一下他的用法。
目前项目背景:vue: ^3.4.29 inquirer: ^10.0.1
| |
| |
| |
| const targetList = [ |
| { |
| name: '张三', |
| value: "\t\t\t\ttarget: 'http://33.33.33.33:3333',", |
| }, |
| { |
| name: '李四', |
| value: "\t\t\t\ttarget: 'http://44.44.44.44:4444',", |
| }, |
| { |
| name: '王二', |
| value: "\t\t\t\ttarget: 'http://22.22.22.22:2222',", |
| }, |
| { |
| name: '麻子', |
| value: "\t\t\t\ttarget: 'http://55.55.55.55:5555',", |
| }, |
| ] |
| |
| const choose = inquirer.prompt([ |
| { |
| type: 'list', |
| name: 'serve', |
| message: '请选择开发环境下需要连接的后端服务', |
| choices: targetList, |
| default: targetList[0].value |
| } |
| ]) |
复制
3) 思路
- 首先使用fs模块读取vite.config.js文件,找到target内容
- 将我们在命令行选中的值 替换掉 刚刚找到target内容
- 将替换成功的内容,重新写入vite.config.js文件
- 在package.json 中npm start 修改命令
4) 完整代码如下:
| |
| |
| import fs from 'fs'; |
| |
| import inquirer from 'inquirer'; |
| |
| |
| |
| |
| const targetList = [ |
| { |
| name: '张三', |
| value: "\t\t\t\ttarget: 'http://33.33.33.33:3333',", |
| }, |
| { |
| name: '李四', |
| value: "\t\t\t\ttarget: 'http://44.44.44.44:4444',", |
| }, |
| { |
| name: '王二', |
| value: "\t\t\t\ttarget: 'http://22.22.22.22:2222',", |
| }, |
| { |
| name: '麻子', |
| value: "\t\t\t\ttarget: 'http://55.55.55.55:5555',", |
| }, |
| ] |
| |
| function findTarget(file) { |
| let arr = file.split('\n') |
| let targetStr = '' |
| for (let i = 0; i < arr.length; i++) { |
| if (arr[i].includes('target:')) { |
| targetStr = arr[i] |
| break |
| } |
| } |
| return targetStr |
| } |
| |
| async function selectServe() { |
| try { |
| |
| const choose = await inquirer.prompt([ |
| { |
| type: 'list', |
| name: 'serve', |
| message: '请选择开发环境下需要连接的后端服务', |
| choices: targetList, |
| default: targetList[0].value |
| } |
| ]) |
| |
| let file = fs.readFileSync('./vite.config.js', 'utf-8') |
| |
| let proxyTarget = findTarget(file) |
| |
| const newFile = file.replace(proxyTarget, choose.serve) |
| |
| fs.writeFileSync('./vite.config.js', newFile) |
| } catch (error) { |
| throw error |
| } |
| } |
| selectServe() |
复制
| |
| |
| "scripts": { |
| "test": "echo \"Error: no test specified\" && exit 1", |
| "dev": "vite --mode development", |
| "build": "vite build --mode production", |
| "builds": "node program/ssh.js && vite build --mode production", |
| "start": "node program/nodeTab.js && vite --mode production", |
| "build:env": "vite build --mode development" |
| }, |
复制
如有不足,欢迎指正。
不要忽视你达成的每个小目标,它是你前进路上的垫脚石。冲!