我目前正在研究由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中選擇一個密鑰對。返回的值用於選擇哪個模塊用於restService。
能夠改變正在使用的模塊是polService
是代碼的目的。
是的,它看起來像ES6模塊不適合在這裏。他們不允許這樣搞亂。 – Bergi