避免使用打字稿声明文件导入import React和ReactDOM

时间:2019-05-27 20:03:31

标签: reactjs typescript jsx

我知道有关此问题的一些信息。 我想轻松地创建许多反应组件,而无需将React导入每个*.tsx文件中。

也许有更好的方法可以实现这一目标,但我只知道一种解决方案: 使用*.d.ts个文件

我有打字稿宠物项目。这是我的tsconfig.json

{
    "compilerOptions": {
        "allowSyntheticDefaultImports": true, 
        "jsx": "react",
        "module": "es6",
        "target": "es5",
        "moduleResolution": "node",
        "strict": true,
        "esModuleInterop": true,
        "noEmitHelpers": true,
        "outDir": "js",
        "rootDir": "src",
        "lib": [
            "dom",
            "es2015"
        ]
    }
}

这是我放置在src目录下的global.d.ts文件

/// <reference path="../../node_modules/@types/react/index.d.ts"/>
/// <reference path="../../node_modules/@types/react-dom/index.d.ts"/>

declare const React: typeof React
declare const ReactDOM: typeof ReactDOM

它工作正常,但我相信有更好的方法。

React是一个命名空间,是否可以将其导出到我的global.d.ts文件中,而不将其声明为const


我尝试使用include中的tsconfig.json选项。它可以工作,但是VSCode没有帮助,看不到tsconfig.json文件中列出的类型

我相信我不了解如何正确地写入d.ts文件,您能帮我吗?

更新

我不想导入React,因为它在全球都可用

<script src="/static/node_modules/react/umd/react.development.js"></script>
<script src="/static/node_modules/react-dom/umd/react-dom.development.js"></script>

更新 我发现是这样的:

import * as react from "react"
import * as react_dom from "react-dom"
import * as reactstrap from "reactstrap"

declare global {
    type React = typeof react
    type ReactDOM = typeof react_dom
    namespace Reactstrap {
        class Nav extends reactstrap.Nav {}
        class NavItem extends reactstrap.NavItem {}
        class NavLink<T> extends reactstrap.NavLink<T> {}
        class Alert extends reactstrap.Alert {}
    }
}

0 个答案:

没有答案