Declare Typescript global variable as "module" type
Solution 1
instead have it as a global
There are two sides to this: global type declaration for typescript and global variable availability for JavaScript consumption.
Global Type Declaration
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").
Global Variable Export
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.
Solution 2
The declare keyword does not declare a variable in the global scope. This keyword is used for cases in which there will be a variable in the global scope and you want to use it in a TypeScript without getting compilation errors.
You can declare a global variable with:
import * as R from "react";
window.R = R;
Solution 3
Like @basarat said, it doesn't look like it's possible. @ahejlsberg himself weighed in on the issue on github: https://github.com/Microsoft/TypeScript/issues/3180#issuecomment-102523512.
Related videos on Youtube
David Faivre
Updated on June 04, 2022Comments
-
David Faivre 12 monthsI 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
Rin 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.tsfile. So assume I've attachedRtowindowalready. Now I need typescript to know thatRis of typeReact module. -
David Faivre about 8 yearsThanks for all the details. I'm interested in the Global Type Declaration part, and was really hoping not to have to hack the react.d.ts file. Seeing as typescript would understandimport * as R from 'react'; var _r = R;I was really wanting a way to just put that in a.d.tsfile. -
basarat about 8 yearsNot technically possible AFAIK considering how the definition is written atm. -
David Faivre about 8 yearsI posted this to the Typescript team -- looks like it's not possible: github.com/Microsoft/TypeScript/issues/… -
David Faivre about 8 yearsMarking as answer, even though there is no answer :(