在ES6模块中定义全局变量的正确方法是什么? [英] What is the correct way to define global variable in ES6 modules?

查看:1834
本文介绍了在ES6模块中定义全局变量的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎找不到对应该从ES6模块导出全局变量的方式的描述.有定义它的资源吗?

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?

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

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

window['v'] = 3;

但是,如果此脚本在Node.js中运行怎么办?那我就没有window了;我有global.但是这段代码不好:

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;

我了解模块的概念,并且不要在我的应用程序中使用全局变量.但是,在控制台中进行调试时使用全局变量可能是有好处的,特别是在使用Webpack等捆绑程序代替SystemJs等加载程序时,可以在控制台中轻松导入模块.

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.

推荐答案

有几种方法可以在应用程序中使用全局值.

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

使用 ES6模块,您可以创建一个从模块导出的常量.然后,您可以从任何其他模块或组件导入它,就像这样:

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

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

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

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

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
}

这篇关于在ES6模块中定义全局变量的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆