繁体   English   中英

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

[英]What is the correct way to define global variable in ES6 modules?

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

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

window['v'] = 3;

但是如果这个脚本在 Node.js 中运行呢? 那我就没有window 我有global . 但是这段代码并不好:

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

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

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

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

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

您可以通过间接 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') 对比?

您可以使用globalThis

 function test(h) { globalThis.testVar = h } test("This is a global var") console.log(testVar)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM