React — Importing Global Variables from the Window Object

Scott Carmichael
1 min readNov 3, 2017

--

When starting a new React project its easy to imagine not using anything from the window object; it feels old-timey and makes your code looks terrible. The thing is though, so many SDKs and third party libraries still (and will always) utilise it. It’s very convenient way of setting and accessing global variables after all.

The compromise I’ve found that works really well is to alias it as a service. A file that lives in the project structure where the variable is declared and exported. This allows the variable to be used as a module more in keeping with the ES6 approach and can be imported into project files when needed.

The benefit of this approach is not having to rewrite (or replace) code that utilises the window object in order to maintain an ES6 coding standard in the project. You can import it and use it like you would a custom component or service class.

Its also a useful way to get around stricter React CLIs and compilers throwing errors when using undeclared global variables. By importing from the alias file, the variable has already been declared meaning further repeat declarations in multiple files can be forgotten about.

--

--