I have the React type definition file (that is declared using an external module). In my source files, I usually do:
import * as R from "react"
and can then happily use R.createElement(...
etc in a strongly typed fashion.
What I want is to not have to import R
in every file, and instead have it as a global declaration (yes, I'm willing to polute the global namespace with a few variables). I've tried:
import * as React from "react";
declare var R : React;
This doesn't work though, I get "Cannot find name 'React'"
. Is there another way to export the entire module as global?
Edit 1 -
I should have made clearer: I'm interested in how to export a global type definition in a .d.ts
file. So assume I've attached R
to window
already. Now I need typescript to know that R
is of type React module
.
instead have it as a global
There are two sides to this: global type declaration
for typescript and global variable availability
for JavaScript consumption.
A .d.ts
or a declaration only contributes to the global name declaration space if there is no root level import or export in the file. So have a file globalreact.d.ts
which will be an edited version of https://github.com/borisyankov/DefinitelyTyped/blob/master/react/react.d.ts of the form declare module R
(instead of declare module "react"
).
You need to put it on window
in case of the browser. So do the following in a file makeReactGlobal.ts
:
var R = require('react');
(<any>window).R = R
And then in your application main
have this file a dependency to ensure that it executes before any of your other code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With