gpt4 book ai didi

javascript - 即时重新包含模块

转载 作者:行者123 更新时间:2023-12-03 04:06:47 25 4
gpt4 key购买 nike

我目前正在处理 SonarQube 确定的 Node.js 应用程序的技术债务。我的应用程序允许在实时数据源和模拟数据源之间进行即时切换。为了实现这一点,我从缓存中销毁了之前的“require”并重新需要它。运行 SonarQube 时,它​​不喜欢“require”语句。它确实建议“导入”语句。然而,这可能不适合这种情况。

现有代码的简化版本:

var config = require('../config');
var polService = require(config.polService);
var root = require('../root');
function doingStuff(liveOrMock) {
setEnvironment(liveOrMock);
delete require.cache[require.resolve(root.path + ‘/config’)];
config = require('../config');
polService = require(config.polService);
}

setEnvironment 函数设置 process.env.NODE_ENV = liveOrMock,该函数在 config.js 中使用。我们使用 module.exports = localOptions[process.env.NODE_ENV]; 导出 config 模块。此代码从 JSON 中选取单个 key 对。返回的值用于选择将哪个模块用于restService。

能够更改 polService 使用的模块是代码的目的。

最佳答案

更改您的 config 模块以导出函数,然后在需要更改环境时调用此函数。

为了使polService成为动态模块,您可以使用dynamic import() 。原生不支持 import(),但您可以使用 this Babel plugin (它与 webpack 一起使用)来转译它。

config.js:

export default () => {
// ...
return localOptions[process.env.NODE_ENV];
}

主要模块:

import getConfig from '../config';

let config = getConfig();

function doingStuff(liveOrMock) {
setEnvironment(liveOrMock);
config = getConfig();
return import(config.polService).then(result => {
polService = result;
});
}

请记住,现在 doingStuff 函数是异步的(即返回一个 Promise),因此您不能直接调用它并立即访问 polService。您必须使用 then() 来等待它方法,或在 async function 中使用 await .

如果您的 polService 模块数量有限,那么预先导入所有模块可能是更好的选择,并且在 doingStuff 函数中只需切换要导入的模块即可polService 变量引用。

import getConfig from '../config';
import polService1 from '../polService1';
import polService2 from '../polService2';
import polService3 from '../polService3';

const polServices = { polService1, polService2, polService3 };

let config = getConfig();
let polService = polService1;

function doingStuff(liveOrMock) {
setEnvironment(liveOrMock);
config = getConfig();
polService = polServices[config.polService];
}

关于javascript - 即时重新包含模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44516680/

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