与Webpack捆绑时,下划线会出错 [英] Underscore gives error when bundling with Webpack

查看:341
本文介绍了与Webpack捆绑时,下划线会出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试重写使用require.js的旧应用程序来使用es6导入。其中一个使用的库是Backbone和Underscore。要创建一个大捆绑包并预编译es6到es5,我使用Webpack与babel-loader。
Bundle被创建,但是当我在浏览器中加载它时,我得到以下错误:

 未捕获TypeError:无法读取属性'_'未定义

似乎Underscore中的'this'在创建的bundle.js中未定义root._给我错误。

  //基线设置
// --------- -----

//在浏览器中建立根对象,window,或在服务器上建立global。
var root = this;

//保存`_`变量的上一个值。
var previousUnderscore = root._;

//建立返回的对象,以循环循环。
var breaker = {}

任何人遇到同样的问题?

解决方案

babel-loader es2015 预设由Babel作为ES6模块处理。在ES6模块中,函数之外的这个 undefined 。在您的情况下,您需要添加

  exclude:/ node_modules /,
/ pre>

到您的 babel-loader config,以便它只处理您自己的代码。目前,您可能还会在所有节点模块上运行Babel,其中许多不期望通过Babel运行,而不是ES6模块。


I am trying to rewrite old application that uses require.js to use es6 imports. One of the used libraries are Backbone and Underscore. To create one big bundle and precompile es6 to es5, I use Webpack with babel-loader. Bundle gets created but when I load it in browser I am getting following error:

Uncaught TypeError: Cannot read property '_' of undefined

It seems that 'this' in Underscore is undefined in created bundle.js so root._ gives me error.

// 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 = {}

Anybody experienced the same issue?

解决方案

Files processed by babel-loader with the es2015 preset are processed by Babel as ES6 modules. In ES6 modules, this outside of functions is undefined. In your case, you need to add

exclude: /node_modules/,

to your babel-loader config so that it will only process your own code. Currently, you are likely running Babel on all of your node modules too, many of which don't expect to be run through Babel and are not intended to be ES6 modules.

这篇关于与Webpack捆绑时,下划线会出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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