【问题标题】:Re-including a module on-the-fly即时重新包含模块
【发布时间】:2017-06-13 08:53:47
【问题描述】:

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

现有代码的简化版:

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 中选择一个密钥对。返回的值用于选择哪个模块用于 restService。

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

【问题讨论】:

  • 是的,看起来 ES6 模块不适合这里。他们不允许这样胡闹。

标签: javascript ecmascript-6 es6-modules


【解决方案1】:

更改您的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 函数是异步的(即返回一个承诺),因此您不能只调用它并立即访问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];
}

【讨论】:

    猜你喜欢
    • 2020-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-17
    • 1970-01-01
    • 1970-01-01
    • 2012-08-14
    相关资源
    最近更新 更多