A while ago we had the need to grab the App
window variable (exposed by CefSharp) and we were extending the Window
interface to do that. There seems to be a better way to get variables that are define in the Window
environment.
I learned this from this link An advanced guide on how to setup a React and PHP.
If you are defining a variable or object you want to read from React (like in CefSharp, o directly in the HTML like in the screenshot)
// inside of your app entry HTML file's header
<script>
var myApp = {
user: "Name",
logged: true
}
</script>
You can do a declare module 'myApp'
in index.d.ts
, then add the myApp
variable as a external library in Webpack's config file
externals: {
myApp: `myApp`,
},
Then you can import as if it was a module in TypeScript (or JavaScript files) with React
import myApp from 'myApp';
And you can even use TypeScript destructuring technique to get internal properties directly
const { user: { name, email}, logged } = myApp;
If you found this useful, you might want to join my newsletter; or take a look at other posts about code, TypeScript, and React.