在 React 中使用全局变量,这些变量在运行时提供,因此在构建时未知 [英] Work with global variables in React which are supplied at runtime and therefore unknown at build time
问题描述
我正在为 Overwolf 开发应用程序 http://developers.overwolf.com/文档/sdk/overwolf/
I am working on a App for Overwolf http://developers.overwolf.com/documentation/sdk/overwolf/
该平台的应用程序是在 Overwolf 浏览器中执行的 html/js 应用程序.浏览器通过全局变量 overwolf
公开 Overwolf API,因此例如对 API 的调用如下所示:
The Apps for this platform are html/js applications executed in the Overwolf Browser. The browser exposes the Overwolf API through a global variable overwolf
so for example a call to the API would look like this:
overwolf.windows.getCurrentWindow(function callback(res) {
var id = res.window.id;
overwolf.windows.close(id, function callback() {
logger.warning("Closing App!");
});
});
(注意没有导入脚本,API由浏览器暴露)我目前正在尝试将我的普通 JS 应用程序迁移到 React,但他们的 API 公开方式面临一些问题.由于我没有导入任何类型的脚本,React 不知道该全局变量,因此无法编译并显示错误:
(Notice that no script is imported, the API is exposed by the browser) I am currently trying to migrate my plain JS application to React and am facing some issues with the way their API is exposed. As I am not importing any kind of script React doesn't know about that global variable and will fail to compile with the error:
第 6 行:'overwolf' 未定义 no-undef
我尝试像这样解决这个问题:
I tried to workaround this problem like this :
const overwolf = typeof overwolf === 'undefined' ?null : overwolf;
在这种情况下,overwolf 将始终被覆盖为 null.如果我像这样尝试
In this instance overwolf would be overwritten to null always. If I try like this
const overwolfGlobal = typeof overwolf === 'undefined' ? null : overwolf;
react 编译器会再次抱怨 typeof overwolf
.
the react compiler will complain about the typeof overwolf
again.
所以我的一般问题是:我如何使用在运行时提供的全局变量,因此 React(和 Webpack)不知道这些变量
So my generic question is: How can I work with global variables which are supplied at runtime and are therefore unknown to React (and Webpack)
推荐答案
您需要在 webpack 配置对象上提供 externals
配置选项.以下内容告诉 Webpack overwolf
库应该可以作为全局变量使用:
You need to provide the externals
configuration option on your webpack config object.
The following tells Webpack that overwolf
library should be available as a global variable:
externals: {
overwolf: {
root: 'overwolf'
}
}
阅读有关 Webpack externals 的更多信息:
Read more about Webpack externals:
防止捆绑某些import
ed包,而是在运行时检索这些外部依赖.
Prevent bundling of certain
import
ed packages and instead retrieve these external dependencies at runtime.
这篇关于在 React 中使用全局变量,这些变量在运行时提供,因此在构建时未知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!