Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lodash unexpectedly injects itself into global when required in subdependency

Tags:

webpack

lodash

My app depends on a library foolib, library foolibhas a dependency on lodash and requires it via var _ = require('lodash')

Requiring foolib results in lodash attaching itself to the window

I found that this was due to this:

https://github.com/lodash/lodash/blob/45785a282442399cfca829aea496104003f773e2/dist/lodash.js#L17041-L17046

  // Some AMD build optimizers, like r.js, check for condition patterns like:
  if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
    // Expose Lodash on the global object to prevent errors when Lodash is
    // loaded by a script tag in the presence of an AMD loader.
    // See http://requirejs.org/docs/errors.html#mismatch for more details.
    // Use `_.noConflict` to remove Lodash from the global object.
    root._ = _;

Adding a debugger into the body of conditional results in the debugger triggering, but the condition that caused the if branch to be entered into now returns false

Adding a console log before the debugger to log out the value of define shows it as being defined by webpack:///(webpack)/buildin/amd-define.js?0bba with the contents of

module.exports = function() { throw new Error("define cannot be used indirect"); };



/*****************
 ** WEBPACK FOOTER
 ** (webpack)/buildin/amd-define.js
 ** module id = 875
 ** module chunks = 2
 **/

Since I'm building with webpack, it seems unexpected that that condition with define and define.amd would be true

like image 271
CheapSteaks Avatar asked Mar 11 '23 12:03

CheapSteaks


1 Answers

Found a solution:
https://github.com/webpack/webpack/issues/138#issuecomment-160638284

module: {
    noParse: /node_modules\/lodash\/lodash\.js/,
}

Added that to webpack config and problem was solved

like image 106
CheapSteaks Avatar answered Apr 27 '23 16:04

CheapSteaks