下划线在与 Webpack 捆绑时出错

Underscore gives error when bundling with Webpack

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

Uncaught TypeError: Cannot read property '_' of undefined

似乎 Underscore 中的 '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 使用 es2015 预设处理的文件由 Babel 作为 ES6 模块处理。在 ES6 模块中,函数之外的 thisundefined。在你的情况下,你需要添加

exclude: /node_modules/,

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

或许,您还有另一种选择,配置如下:

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

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