ES6 and window / global variables
I am working with es6 modules. In some of them, I use lodash. My question is, is it possible to load lodash as a global variable, or should it be imported into all files separately? I tried this in my initializer:
import lodash from 'lodash';
window._ = lodash;
Also like this:
window._ = require('lodash');
But that won't work. In my modules, I get errors when using for example _.truncate:
TypeError: Cannot read property "truncate" from undefined
source to share
There are three ways to resolve this if you are using webpack.
-
window
the object is still available. Just like your example, you need to make sure the initializer is loaded first, and then you can attach the underline to the window object just like you do, and then in your module you can use it likewindow._.truncate
. You can see the disadvantages here: 1) There is a load order dependency. 2) There is a dependency on the window object. 3) The use is not very pleasant. -
You can import
underscore
directly for the required module. -
With webpack you can define a global variable define plugin https://webpack.js.org/plugins/define-plugin/ Then in each module you can use
_.truncate
as desired.
If you only need a module occasionally, # 2 is the way to go. If you plan on using it often, then # 3 will be more convenient. # 1 is always ugly, but on rare occasions, such a workaround might help, although your case seems to be different.
source to share