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
It's like a global variable, and it should be straightforward if we have everything in one file, for example: var globalTooltips = []; function veryComplicatedProcess(data){ //some complicated logic const newData = shapeMe(data) saveData(newData); // additional task const tooltips = getTooltips(newData.
In HTML, the global scope is the window object. All global variables belong to the window object. Your global variables (or functions) can overwrite window variables (or functions).
The global object provides variables and functions that are available anywhere. By default, those that are built into the language or the environment. In a browser it is named window , for Node. js it is global , for other environments it may have another name.
What is a global object in JavaScript? The global object in JavaScript is an always defined object that provides variables and functions, and is available anywhere. In a web browser, the global object is the window object, while it is named global in Node.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With