将Typescript全局变量声明为“模块".类型 [英] Declare Typescript global variable as "module" type
问题描述
我有React类型定义文件(使用外部模块声明).在我的源文件中,我通常这样做:
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"
,然后可以很强地使用R.createElement(...
等.
and can then happily use R.createElement(...
etc in a strongly typed fashion.
我想要的是不必在每个文件中导入R
,而是将其作为全局声明(是的,我愿意用几个变量来污染全局名称空间).我尝试过:
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;
这不起作用,我得到了"Cannot find name 'React'"
.还有另一种方法可以将整个模块导出为全局模块吗?
This doesn't work though, I get "Cannot find name 'React'"
. Is there another way to export the entire module as global?
编辑1 -
我应该更清楚一点:我对如何在.d.ts
文件中导出全局类型定义感兴趣.因此,假设我已经将R
附加到window
.现在我需要打字稿才能知道R
的类型是React module
.
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
这有两个方面:global type declaration
用于打字稿,global variable availability
用于JavaScript使用.
There are two sides to this: global type declaration
for typescript and global variable availability
for JavaScript consumption.
如果.d.ts
或声明中没有根级别 import 或 export ,则声明仅对 global 名称声明空间起作用.文件.因此,有一个文件globalreact.d.ts
将是declare module R
(而不是declare module "react"
).
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"
).
如果使用浏览器,则需要将其放在window
上.在文件makeReactGlobal.ts
中执行以下操作:
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
然后在您的应用程序main
中使此文件具有依赖性,以确保它在您的任何其他代码之前执行.
And then in your application main
have this file a dependency to ensure that it executes before any of your other code.
这篇关于将Typescript全局变量声明为“模块".类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!