Jakob Nielsen
Jakob Nielsen

Reputation: 5198

Work with global variables in React which are supplied at runtime and therefore unknown at build time

I am working on a App for Overwolf http://developers.overwolf.com/documentation/sdk/overwolf/

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!");
    });
});

(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:

Line 6: 'overwolf' is not defined no-undef

I tried to workaround this problem like this :

const overwolf = typeof overwolf === 'undefined' ? null : overwolf;

In this instance overwolf would be overwritten to null always. If I try like this

const overwolfGlobal = typeof overwolf === 'undefined' ? null : overwolf;

the react compiler will complain about the typeof overwolf again.

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)

Upvotes: 1

Views: 493

Answers (1)

Carloluis
Carloluis

Reputation: 4320

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'
  }
}

Read more about Webpack externals:

Prevent bundling of certain imported packages and instead retrieve these external dependencies at runtime.

Upvotes: 3

Related Questions