Search code examples
javascriptecmascript-6ecmascript-5es6-modules

re-export or dynamically export object based on condition


Here is the simple scenario, I am struggling with

apicontainer.js

import mockApi from './mock-api';
import realApi from './api';
function getApi() {
   return Cookies.get('isMock') ? mockApi: realApi;
}
let api = getApi();
export function changeApi() {
    api = getApi();
}
export default api

somepage.js

import api from './path-to/apicontainer';

After the application gets loaded, If set/remove cookie and call changeApi method, will it change the reference dynamically and returns the right api or Is there a better solution?


Solution

  • Yes, imported bindings are just references to the exported variables. One does not export the value, one makes the variable itself available (readonly from outside, though).

    So you can do

    // apicontainer.js
    import mockApi from './mock-api';
    import realApi from './api';
    function getApi() {
       return Cookies.get('isMock') ? mockApi: realApi;
    }
    let api = getApi();
    export { api as default }
    export function changeApi() {
        api = getApi();
    }
    

    // somepage.js
    import api, {changeApi} from 'apicontainer'
    changeApi();