babel-plugin-lodash icon indicating copy to clipboard operation
babel-plugin-lodash copied to clipboard

Lodash is set to undefined in build if its loaded onto a local 'this'

Open usman-subhani opened this issue 5 years ago • 4 comments

Issue occurs in this situation

import _ from 'lodash';

class test {
  constructor() {
    this._ = _; // lodash is replaced with 'undefined' here
  }
  someMethod() {
    const value = this._.get({a:1}, 'a'); // error thrown here because this._ is undefined
  }
}

usman-subhani avatar Jan 04 '20 04:01 usman-subhani

Hi @usman-subhani!

Can you post what the transpiled code looks like?

jdalton avatar Jan 07 '20 00:01 jdalton

Hey @jdalton, sure. This is the transpiled code with the plugin

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "test", function() { return test; });
class test {
  constructor() {
    this._ = undefined; // lodash is replaced with 'undefined' here
  }

  someMethod() {
    const value = this._.get({
      a: 1
    }, 'a'); // error thrown here because this._ is undefined

  }

}

and this is the code after removing the plugin

/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "test", function() { return test; });
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_0__);

class test {
  constructor() {
    this._ = lodash__WEBPACK_IMPORTED_MODULE_0___default.a; // lodash is imported and set here
  }

  someMethod() {
    const value = this._.get({
      a: 1
    }, 'a'); // works fine now

  }

}

This is the .babelrc config

{
  "presets": [
    "@babel/preset-react",
    ["@babel/preset-env", {
      "targets": {
        "chrome": "72",
        "firefox": "64",
        "opera": "50",
        "node": "current"
      }
    }]
  ],
  "plugins": ["lodash", "@babel/plugin-transform-runtime"]
}

I have v3.3.4 of babel-plugin lodash

usman-subhani avatar Jan 07 '20 10:01 usman-subhani

Have the same issue: lodash is being replaced with undefined. If I disable babel-plugin-lodash, the reference is preserved.

drudv avatar Sep 08 '20 19:09 drudv

Have the same issue: lodash is being replaced with undefined. If I disable babel-plugin-lodash, the reference is preserved.

same issue, is there a solution now?

JackieCheung avatar Jan 28 '21 17:01 JackieCheung