【问题标题】:Underscore gives error when bundling with Webpack与 Webpack 捆绑时,下划线会出错
【发布时间】:2016-09-02 22:21:49
【问题描述】:

我正在尝试重写使用 require.js 的旧应用程序以使用 es6 导入。使用的库之一是 Backbone 和 Underscore。为了创建一个大包并将 es6 预编译为 es5,我使用 Webpack 和 babel-loader。 Bundle 已创建,但是当我在浏览器中加载它时出现以下错误:

Uncaught TypeError: Cannot read property '_' of undefined

似乎下划线中的“this”在创建的 bundle.js 中未定义,所以 root._ 给了我错误。

// Baseline setup
// --------------

// Establish the root object, `window` in the browser, or `global` on   the server.
var root = this;

// Save the previous value of the `_` variable.
var previousUnderscore = root._;

// Establish the object that gets returned to break out of a loop   iteration.
var breaker = {}

有人遇到过同样的问题吗?

【问题讨论】:

  • 你的babel-loader webpack 配置是什么?您可能遗漏了 exclude: /node_modules/ 的内容。
  • Tnx 很多!将exclude: /node_modules/ 添加到babel-loader webpack 配置解决了问题!

标签: javascript ecmascript-6 webpack underscore.js


【解决方案1】:

babel-loader 处理的带有es2015 预设的文件被 Babel 作为 ES6 模块处理。在 ES6 模块中,函数外的thisundefined。在您的情况下,您需要添加

exclude: /node_modules/,

到您的babel-loader 配置,以便它只处理您自己的代码。目前,您可能也在所有节点模块上运行 Babel,其中许多不希望通过 Babel 运行,也不打算成为 ES6 模块。

【讨论】:

    【解决方案2】:

    也许,您可以通过以下配置为您提供另一种选择:

    {
        "presets": [
            ["es2015", {
                "modules": false
            }]
        ]
    }
    

    原因在issue中有详细描述:https://github.com/babel/babel/issues/4720

    【讨论】:

      猜你喜欢
      • 2016-01-05
      • 2020-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-27
      • 2019-08-16
      • 2018-03-12
      相关资源
      最近更新 更多