当从属关系中需要时,Lodash意外地将自身注入到全局中 [英] Lodash unexpectedly injects itself into global when required in subdependency

查看:166
本文介绍了当从属关系中需要时,Lodash意外地将自身注入到全局中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序依赖于库foolib,库foolib依赖于lodash,并需要通过var _ = require('lodash')

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

需要foolib会导致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._ = _;

将调试器添加到条件主体中会触发调试器,但是导致进入if分支的条件现在返回false

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

在调试器中添加控制台日志以注销define的值,表明它是由webpack:///(webpack)/buildin/amd-define.js?0bba定义的,其内容为

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
 **/

自从我使用webpack进行构建以来,使用definedefine.amd的条件似乎是真的

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

推荐答案

找到了解决方案:
https://github.com/webpack/webpack/webpack/issues/138#issuecomment-160638284

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

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

将其添加到webpack配置中,问题已解决

Added that to webpack config and problem was solved

这篇关于当从属关系中需要时,Lodash意外地将自身注入到全局中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆