What is the correct way to define a global variable in ES6 modules?

I cannot find a description of how I should export a global variable from an ES6 module. Is there a resource where it is defined?

The only solution that seems to work is referencing a global object, such as window :

 window['v'] = 3; 

But what if these scripts work in Node.js? Then I do not have window ; I have global . But this code is not very good:

 var g = window || global; g['v'] = 3; 

I understand the concept of modules and do not use global variables in my applications . However, having global variables during debugging in the console can be useful, especially when using packages such as Webpack, rather than loaders like SystemJ, where you can easily import the module into the console.

+8
javascript ecmascript-6 module
source share
1 answer

There are several ways to have global values ​​in your application.

Using ES6 modules , you can create a constant that you export from your module. Then you can import this from any other module or component, for example:

 /* Constants.js */ export default { VALUE_1: 123, VALUE_2: "abc" }; /* OtherModule.js */ import Constants from '../Constants'; console.log(Constants.VALUE_1); console.log(Constants.VALUE_2); 

Alternatively, some JS binding tools provide a way to pass values ​​to your components at build time.

For example, if you use Webpack , you can use DefinePlugin to configure several available constants at compile time, for example:

 /* Webpack configuration */ const webpack = require('webpack'); /* Webpack plugins definition */ new webpack.DefinePlugin({ 'VALUE_1': 123, 'VALUE_2': 'abc' }); /* SomeComponent.js */ if (VALUE_1 === 123) { // do something } 
0
source share

All Articles