在 ES6 模块中定义全局变量的正确方法是什么?

问题描述 投票:0回答:3

我似乎找不到如何从 ES6 模块导出全局变量的描述。是否有定义它的资源?

唯一可行的解决方案是引用全局对象,例如

window

window['v'] = 3;

但是如果这个脚本在 Node.js 中运行怎么办?那我就没有

window
;我有
global
。但这段代码并不好:

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

我理解模块的概念并且不在我的应用程序中使用全局变量。然而,在控制台调试期间拥有全局变量可能是有益的,特别是当使用 Webpack 这样的捆绑器而不是 SystemJs 这样的加载器时,您可以轻松地在控制台中导入模块。

javascript module ecmascript-6
3个回答
21
投票

有多种方法可以在您的应用程序中使用全局值。

使用 ES6 模块,您可以创建一个从模块导出的常量。然后,您可以从任何其他模块或组件导入它,如下所示:

/* 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);

或者,一些 JS 捆绑工具提供了一种在构建时将值传递到组件中的方法。

例如,如果您使用Webpack,则可以使用DefinePlugin来配置一些在编译时可用的常量,如下所示:

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

4
投票

您可以通过间接 eval 调用来获取全局对象。

// 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";

您必须注意模块的加载方式,以确保正确的排序。

更多信息:JavaScript 中的 (1, eval)('this') 与 eval('this') ?


4
投票

您可以使用

globalThis

function demo(h) {
    globalThis.testVar = h
}

demo("This is a global variable.")
console.log(testVar)

© www.soinside.com 2019 - 2024. All rights reserved.