Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 and window / global variables

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

like image 935
Karolis Tička Avatar asked Mar 24 '17 18:03

Karolis Tička


People also ask

How do I declare a global variable in ES6?

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.

Is window a global variable?

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).

Is global the same as window?

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.

Is window a global object of JavaScript?

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.


1 Answers

There are 3 ways to allow this seeing you are using webpack.

  1. 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.

  2. You can import underscore directly for the module needed.

  3. 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.

like image 194
Billy Chan Avatar answered Nov 02 '22 19:11

Billy Chan