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
// 需要定義,命令行可選范圍
// name是展示在命令行
// value是選中name后可獲得相對的value
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',",},
]
// 調用inquirer方法,進行基礎配置
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) 完整代碼如下:
// nodeTab.js
// Vue2中引入fs模塊使用require,Vue3使用import
import fs from 'fs';
// inquirer這個庫來創建交互式的命令行界面
import inquirer from 'inquirer';// 需要定義,命令行可選范圍
// name是展示在命令函
// value用來替換proxy中代碼
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',",},
]
// 去找到target這一行代碼
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}])// 讀取了文件vite.config.js為string格式let file = fs.readFileSync('./vite.config.js', 'utf-8')// 找到target這一行let proxyTarget = findTarget(file)// 替換我們新選的后端服務地址const newFile = file.replace(proxyTarget, choose.serve)// 重新寫入vite.config.jsfs.writeFileSync('./vite.config.js', newFile)} catch (error) {throw error}
}
selectServe()
// package.json
// 這里就展示部分代碼,在start啟動項目前,先執行node program/nodeTab.js這個腳本"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"},
如有不足,歡迎指正。
不要忽視你達成的每個小目標,它是你前進路上的墊腳石。沖!