ES6 and window / global variables
Asked Answered
F

1

9

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

Farant answered 24/3, 2017 at 18:55 Comment(2)
I would suggest importing it in all files separately. The point of module imports is to make your dependencies clear.Erinaceous
Also, if you include modules in multiple scripts, it loads as a Singleton so you're not duplicating your module.Dzoba
Z
6

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.

Zuleika answered 25/3, 2017 at 7:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.