I'm working with es6 modules. In some of them I use lodash. My question is - is it possible to load lodash as global variable, or it should be imported in all files separately? I tried this in my initializer:
import lodash from 'lodash';
window._ = lodash;
Also this way:
window._ = require('lodash');
But it doesn't work. In my modules I get errors when use, for example, _.truncate:
TypeError: Cannot read property 'truncate' of undefined
There are 3 ways to allow this seeing you are using webpack.
window
object is still available. Just as your example, you need to ensure the initializer is loaded at first, and then you can attach underscore to window object as you did, then in your module you can use it as window._.truncate
. You can see the drawbacks here are: 1) There is a loading order dependency. 2) There is dependency on window object. 3) The usage is not nice.
You can import underscore
directly for the module needed.
With webpack, you can define global variable by define plugin https://webpack.js.org/plugins/define-plugin/ Then in every module you could use _.truncate
at will.
If you only need the module occasionally, #2 is the way to go. If you expect to use it frequently then #3 will be more convenient. #1 is always ugly but in rare circumstance such workaround might help, though your case apparently is not.