在 ES6 模块中定义全局变量的正确方法是什么?
我似乎找不到关于如何从 ES6 模块导出全局变量的描述。是否有定义它的资源?
唯一可行的解决方案似乎是引用全局对象,例如 window:
window['v'] = 3;
但是如果此脚本在 Node.js 中运行怎么办?那我就没有window
;我有全局
。但这段代码并不好:
var g = window || global;
g['v'] = 3;
我理解模块的概念并且不在我的应用程序中使用全局变量。但是,在控制台中调试期间拥有全局变量可能会很有用,特别是当使用 Webpack 等捆绑器而不是 SystemJs 等加载器时,您可以在控制台中轻松导入模块。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的应用程序中有几种可以使用全局值的方法。
使用 ES6模块,您可以创建一个从模块导出的常数。然后,您可以从任何其他模块或组件中导入此信息,例如:
另外,某些JS捆绑工具提供了一种在构建时间将值传递到组件中的方法。
例如,如果您使用的是 webpack ,则可以使用 defineplugin < /a>在编译时配置一些可用的常数,例如:
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:
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:
您可以使用
globalthis
:You can use
globalThis
:您可以使用间接评估调用来获取全局对象。
您必须注意模块的加载方式,以确保正确订购。
更多信息:(1,eval)在JavaScript?中
You can grab the global object with an indirect eval call.
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?