寻找优雅且简单的解决方案来拥有“本地配置覆盖”文件。
这个想法是能够进行本地配置,而不会每次都要求添加到 git 存储库。
为此,我需要包含 local.config.js 如果存在的话。
我在
config.js
中有全局应用程序配置,配置如下
export const config = {
API_URL="https://some.host",
}
和
config.local.js
export const config = {
API_URL="https://other.address",
}
有
.gitignore
:
config.local.js
难度:
我不想仅仅为了这一件事而向项目添加节点模块。我相信应该有一种优雅的方法可以用一行或几行来完成此操作,但到目前为止还没有找到。
我尝试过的事情:
1.
try {
const {
apiUrl: API_URL,
} = require('./config.local.js');
config. API_URL =apiUrl;
} catch (e) {
}
require
在 try{} 块内不起作用。
2.
const requireCustomFile = require.context('./', false, /config.local.js$/);
requireCustomFile.keys().forEach(fileName => {
requireCustomFile(fileName);
});
不起作用。
3.
export const config = require('./config.local.js') || {default:'config = {...}'}
不起作用。
4.
使用 .env 和设置环境变量:我需要覆盖整个配置值数组。就不一一列举了
此解决方案使用
process.argv
。它是节点本机的,如记录在这里并且不使用.env
它检查用于启动应用程序的命令值。由于本地环境和生产环境之间的这些应该有所不同,因此这是一种无需额外模块即可轻松切换的方法。
启动节点应用程序的命令提示符: (如果您使用这种方法,这也可能在
package.json
中并通过 npm start
产生。)
$ node index.js local
节点应用程序的index.js:
var express = require('express');
var config = require('./config');
if (process.argv[2] === 'local') {
// the 3rd argument provided at startup (2nd index) was 'local', so here we are!
config = require('./config_local');
}
var app = express();
// rest of owl…
这应该适用于任何地方,甚至是组件库。
const config = {...};
let localConfig = {};
try {
localConfig = require("./local.config").default;
} catch {
// There's no local config, nothing to override.
}
export default {
...config,
...localConfig,
};
const config = {...};
export default config;