外部配置文件
- 打包过后,为了在生产环境去自定义服务的基地址来配置项目根目录下的文件
config.json
// config.json
{
"baseUrl": "127.0.0.1:50051"
}
- 在打包后,需要将
config.json
文件暴露在生产环境的目录下,需配置打包环境vue.config.js
module.exports = defineConfig({
pluginOptions: {
electronBuilder: {
builderOptions: {
extraResources: [
{ "from": "config.json", "to": "."}
]
}
}
}
})
此时,在打包目录resources
下可以看见配置文件config.json
- 打包成功暴露
config.json
文件后,需要在代码中使用到config.json
中的配置,新建js
文件
/**
* [ getBaseUrl.js ]
*/
const fs = require('fs');
const path = require('path');
// 获取配置文件的绝对路径(假设在 Electron 项目的根目录下)
const configFilePath = path.join(__dirname, '..', 'config.json');
// 读取配置文件的内容
const readConfigFile = () => {
try {
const configData = fs.readFileSync(configFilePath, 'utf-8');
return JSON.parse(configData);
} catch (error) {
console.error('Error reading config file:', error);
return error;
}
};
module.exports = {
readConfigFile,
};
使用node
中的fs
模块去读取配置文件
/**
* 其他文件可以去使用配置文件信息
*/
const { readConfigFile } = require('../getBaseUrl')
const config = readConfigFile()
const ip = config.baseUrl || ""
此时就成功了!