Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/392.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 我们在飞行中包括一个模块_Javascript_Ecmascript 6_Es6 Modules - Fatal编程技术网

Javascript 我们在飞行中包括一个模块

Javascript 我们在飞行中包括一个模块,javascript,ecmascript-6,es6-modules,Javascript,Ecmascript 6,Es6 Modules,我目前正在处理SonarQube为Node.js应用程序确定的技术债务。我的应用程序允许在实时数据源和模拟数据源之间进行动态切换。为了实现这一点,我从缓存中销毁以前的“require”并重新请求它。运行SonarQube时,它不喜欢“require”语句。它确实建议使用“导入”语句。但是,在这种情况下,这可能不合适 现有代码的简化版本: var config = require('../config'); var polService = require(config.polService);

我目前正在处理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\u env=liveOrMock
,该函数用于
config.js
。我们使用
module.exports=localOptions[process.env.NODE_env]导出
config
模块此代码从JSON中选择单个密钥对。返回的值用于选择restService使用的模块


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

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

要使
polService
成为动态模块,您可以使用<代码>导入()
本机不受支持,但您可以使用(它与网页包一起使用)对其进行传输

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
。您必须通过使用方法或在中使用
wait
来等待它

如果您的
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];
}

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