Underscore gives error when linking to Webpack

I am trying to rewrite an old application that uses require.js to use es6 import. One of the libraries used is Backbone and Underscore. To create one large package and pre-build es6 on es5, I use Webpack with the babel loader. The bundle is created, but when I load it in the browser, I get the following error:

Uncaught TypeError: Cannot read property '_' of undefined 

It seems that 'this' in Underscore is undefined in the created .js package, so root._ gives me an 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 = {} 

Has anyone experienced the same issue?

+6
source share
1 answer

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

 exclude: /node_modules/, 

into the babel-loader configuration so that it only processes your own code. You are currently probably using Babel on all of your node modules, many of which do not expect them to run through Babel and are not intended for ES6 modules.

+20
source

All Articles