我似乎找不到从ES6模块导出全局变量的方式的描述。是否存在定义的资源?
似乎有效的唯一解决方案是引用全局对象,例如window
:
window['v'] = 3;
但是如果这个脚本在Node.js中运行怎么办?然后我没有window
;我有global
。但是这段代码并不好:
var g = window || global;
g['v'] = 3;
我理解模块的概念,不在我的应用程序中使用全局变量。但是,在控制台中调试期间使用全局变量可能是有益的,尤其是在使用Webpack等捆绑器而不是像SystemJs这样的加载器时,您可以在控制台中轻松导入模块。
答案 0 :(得分:9)
有几种方法可以在您的应用程序中使用全局值。
使用 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
}
答案 1 :(得分:1)
您可以使用globalThis
:
function test(h) {
globalThis.testVar = h
}
test("This is a global var")
console.log(testVar)
答案 2 :(得分:0)
您可以通过间接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";
您必须注意模块的加载方式,以确保正确的顺序。