带有声明文件的打字稿'Cannot find module'



我在react中使用typescript,需要为一个名为react-sticky的第三方库提供类型。我不想发布typings模块,我只想编写类型并将它们包含在我的代码库中,但我遇到了麻烦。下面是设置

App.tsx

/// <reference path="./typings/index.d.ts" />
/// <reference path="./typings/react-sticky.d.ts" />
import * as React from "react"
import { Sticky, StickyContainer } from "react-sticky"
const App: React.StatelessComponent<{}> = () => {
    return <StickyContainer>
        <Sticky>
        <h1>Hello World</h1>
        </Sticky>
    </StickyContainer>
}

/typings/react-sticky.d.ts

/// <reference path="./modules/react/index.d.ts" />
import * as React from "react"
declare module "react-sticky" {
    export var StickyContainer: React.Component<{}, {}>
    export interface StickyProps {
        stickyStyle?: any
        stickyClassName?: string
        topOffset?: number
        bottomOffset?: number
        className?: string
        style?: {}
        onStickyStateChange?: () => void
        isActive?: boolean
    }
    export var Sticky: React.Component<StickyProps, {}>
}

typings/index.d.ts

/// <reference path="modules/react-dom/index.d.ts" />
/// <reference path="modules/react/index.d.ts" />
/// <reference path="react-sticky.d.ts" />

我得到的错误如下

App.tsx(3,41): error TS2307: Cannot find module 'react-sticky'.
现在,我是Typescript的新手,这里很可能有多个错误,有人知道我需要做什么吗?

你就快成功了。由于这是您第一次声明模块'react-sticky', (<>在其他地方增加声明),因此您必须将import语句放在模块声明中。您的声明文件可能看起来像这样:

// custom_typings/react-sticky.d.ts
declare module "react-sticky" {
  import * as React from "react"
  var StickyContainer: React.ComponentClass<{}>
  interface StickyProps {
    stickyStyle?: any
    stickyClassName?: string
    topOffset?: number
    bottomOffset?: number
    className?: string
    style?: {}
    onStickyStateChange?: () => void
    isActive?: boolean
  }
  var Sticky: React.ComponentClass<StickyProps>
}

有趣的事实:

    你不需要在你的声明文件中添加导出
  • 你不需要在任何地方添加///引用,只要你不把你的声明文件放在你的项目的根目录。

相关内容

最新更新