lodash / babel-plugin-lodash

Modular Lodash builds without the hassle.
Other
1.96k stars 91 forks source link

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

Open usman-subhani opened 4 years ago

usman-subhani commented 4 years ago

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
  }
}
jdalton commented 4 years ago

Hi @usman-subhani!

Can you post what the transpiled code looks like?

usman-subhani commented 4 years ago

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

drudv commented 3 years ago

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

JackieCheung commented 3 years ago

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?