What is the correct way to define global variable

2020-05-29 16:29发布

问题:

I can't seem to find a description of the way I should export global variable from ES6 module. Is there a resource where it's defined?

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

window['v'] = 3;

But what if this scripts runs in Node.js? Then I don't have window; I have global. But this code is not good:

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

I understand the concept of modules and don't use globals in my applications. However, having global variables during debugging in the console may be beneficial, especially when using bundlers like Webpack instead of loaders like SystemJs where you can easily import a module in a console.

回答1:

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

Using ES6 modules, you can create a constant which you export from your module. You can then import this from any other module or component, like so:

/* 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 bundling tools provide a way to pass values into your components at build time.

For example, if you're using Webpack, you can use DefinePlugin to configure a few constants available at compile time, like so:

/* 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
}


回答2:

You can grab the global object with an indirect eval call.

// this weird syntax grabs the global object
const global = (0,eval)("this");
// (0,eval) === eval; but the first one is an indirect evaluation
// inside indirect evaluation of eval, "this" is global object
// this takes advantage of that fact to identify "global"

// then set whatever global values you need
global.VALUE_1 = 123;
global.VALUE_2 = "abc";

You'll have to take care with the way your modules are loaded to ensure proper ordering.

more info: (1, eval)('this') vs eval('this') in JavaScript?