即时重新包含模块

时间:2017-06-13 08:53:47

标签: javascript ecmascript-6 es6-modules

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

现有代码的简化版本:

protected virtual IMessageActivity MakePrompt(IDialogContext context, string prompt, IReadOnlyList<U> options = null, IReadOnlyList<string> descriptions = null, string speak = null)
{
    var msg = context.MakeMessage();

    // force Culture
    CultureInfo lang = ...;
    if (lang != null)
    {
        Thread.CurrentThread.CurrentCulture = lang;
        Thread.CurrentThread.CurrentUICulture = lang;
        context.Activity.AsMessageActivity().Locale = lang.ToString();
    }

    if (options != null && options.Count > 0)
    {
        promptOptions.PromptStyler.Apply(ref msg, prompt, options, descriptions, speak);
    }
    else
    {
        promptOptions.PromptStyler.Apply(ref msg, prompt, speak);
    }
    return msg;
}

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导出config模块。此代码从JSON中选择一个密钥对。返回的值用于选择正在用于restService的模块。

能够更改module.exports = localOptions[process.env.NODE_ENV];使用的模块是代码的目的。

1 个答案:

答案 0 :(得分: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];
}