gpt4 book ai didi

javascript - 简单而优雅的方法来覆盖本地文件如果存在?

转载 作者:太空宇宙 更新时间:2023-11-04 01:27:09 31 4
gpt4 key购买 nike

寻找优雅且简单的解决方案来拥有“本地配置覆盖”文件。

这个想法是能够拥有本地配置,而不会每次都要求添加到 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

难度:
我不想仅仅为了这一件事而向项目添加 Node 模块。我相信应该有一种优雅的方法可以在一行或几行内完成此操作,但到目前为止还没有找到。

我尝试过的事情:

1.

try {
const {
apiUrl: API_URL,
} = require('./config.local.js');
config. API_URL =apiUrl;
} catch (e) {

}

require 在 try{} block 内不起作用。

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。它是 Node native 的 documented here并且不使用 .env

它检查用于启动应用程序的命令值。由于本地环境和生产环境之间的这些应该有所不同,因此这是一种无需额外模块即可轻松切换的方法。

启动 Node 应用程序的命令提示符:(如果您使用这种方法,这也可能位于 package.json 中,并通过 npm start 产生。)

$ node index.js local

Node 应用程序的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…

关于javascript - 简单而优雅的方法来覆盖本地文件如果存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57155890/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com