reactjslodashtranspiler

What is this transpiled code in my react application?


In my React application, I'm using the lodash function set like this:

set(objectToSet, fieldInObjectToSet, valueToSet);

When I look at the transpiled code, I see that this line gets converted to this:

(0,lodash__WEBPACK_IMPORTED_MODULE_2__.set)(objectToSet, fieldInObjectToSet, valueToSet);

What is this part: (0,lodash__WEBPACK_IMPORTED_MODULE_2__.set)?

It looks like something that references the set function, but what is the leading 0? This also looks like an argument list to a nameless function. Is that what this is?

Thanks!


Solution

  • For patterns like this are called indirect function call:

    (0, _.set)(...)
    

    The point of this pattern is to return the set function from _ and call it but without the calling context _, with comma operator. The 0 is arbitrary and irrelevant, similar to 0 in void 0, it can literally be anything.

    The reason the transpiler doing this is because you called it like

    import { set } from 'lodash';  // or similar import
    set(...);
    

    but not

    import _ from 'lodash'; 
    _.set(...)
    

    The difference here is trivial, or none at all. But the transplier is doing this to make sure it's always the same behavior without ES6 Modules.

    To demonstrate this discrepancy better, here's a minimal example:

    window.name = 'window';
    
    const foo = {
      name: 'foo',
      greeting() {
        console.log(`Hello, I'm ${this.name}!`);
      }
    };
    
    // this function is called with calling context of `foo`
    foo.greeting();       // > hello, I'm foo
    
    // this function is called with calling context of the current scope, which is `window`
    (0, foo.greeting)();  // > hello, I'm window
    
    // which is essentially equivolent to
    const { greeting } = foo;
    greeting();           // > hello, I'm window