2017-06-13 78 views
0

我目前正在研究由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是代碼的目的。

+0

是的,它看起來像ES6模塊不適合在這裏。他們不允許這樣搞亂。 – Bergi

回答

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]; 
}