简体   繁体   中英

ES6: self-import vs ordering exports for referencing

I have a single file that has utils methods. Each is exported individually. I am in a situation where one util requires another. I currently define the functions used before they're used. But I came across ES6's cyclic dependency and using that removes the need to meticulously organize the util functions. Is there any reason I should not use that?

Simplified eg: Currently:

  export const safeParsing = (str) =>  { 
    try { return JSON.parse(str); }
    catch (e) { return {}; }
  };

  export const parseToken = (t) => safeParsing(t); 

Using cyclic dep:

import * as self from 'src/jsUtils';

export const parseToken = (t) => self.safeParsing(t);
export const safeParsing = (str) => {...}

Edit: Using cyclic imports also enables me to spyOn (Jest) inner functions. Eg:

 test('parseToken uses safe parsing', () => { ... spyOn safeParsing ... });

Relevant refs:

ES6 modules: Export single class of static methods OR multiple individual methods

https://stackoverflow.com/a/40242291/958598

https://stackoverflow.com/a/35225936/958598

https://stackoverflow.com/a/55193363/958598

If you define them as ordinary functions with function safeParsing() {... } rather than assigning them to a const variable, then ordering no longer matters because all function definitions are hoisted to the top of the scope.So, you can use all functions in any order. If you do const safeParsing =... then you have to very carefully order the declarations because they can't be used until after they are assigned. This is one of the reasons I use the regular named function declarations rather than function expressions (like you show).

And, you can still do export function safeParsing() {...} . Just make your definitions be function declarations, not function expressions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM