Javascript 我们在飞行中包括一个模块
我目前正在处理SonarQube为Node.js应用程序确定的技术债务。我的应用程序允许在实时数据源和模拟数据源之间进行动态切换。为了实现这一点,我从缓存中销毁以前的“require”并重新请求它。运行SonarQube时,它不喜欢“require”语句。它确实建议使用“导入”语句。但是,在这种情况下,这可能不合适 现有代码的简化版本: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);
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模块不适合这里。他们不允许这样胡闹。