【问题标题】:Creating a d.ts file for existing module为现有模块创建 d.ts 文件
【发布时间】:2015-11-20 03:09:48
【问题描述】:

我正在尝试为React StaticContainer 库创建一个d.ts 文件。

在 NPM 中安装的 lib 如下所示:

var React = require('react');

var StaticContainer = (function (_React$Component) {

  function StaticContainer() {
    // ...
  }

  // ...

  return StaticContainer;
})(React.Component);

module.exports = StaticContainer;

示例用法如下:

var StaticContainer = require('react-static-container');

而且我不确定如何为此创建声明并在 TypeScript 中使用它。到目前为止,我的研究得出了这个结论:

import * as StaticContainer from 'react-static-container'

还有这个d.ts 文件:

interface StaticContainer extends React.Component<any, any> {
  shouldUpdate?:boolean;
}

declare module "react-static-container" {
  export = StaticContainer;
}

但是 TSC 给了我这个错误:

错误:(3, 34) TS2497: Module '"react-static-container"' 解析为非模块实体,无法使用此构造导入。

我很困惑module.exports = StaticContainer 应该如何转换为d.ts 文件。这是怎么做到的?

【问题讨论】:

    标签: module typescript


    【解决方案1】:

    Module '"react-static-container"' 解析为非模块实体,无法使用此构造导入。

    正是错误所说的。您需要使用import require 导入export = 样式库。这是因为 ES6 规范。

    import StaticContainer =  require('react-state-container');
    

    【讨论】:

    • 我确定它的意思是说什么,大多数错误消息都是这样;)但我没有上下文来理解它......“这是因为 ES6 规范”不幸的是没有' t进一步我的理解。你能详细说明吗?您发布的代码不起作用,现在我得到TS2304: Cannot find name 'StaticContainer'. 我猜我的d.ts 没有正确反映原始库的导出方式。
    • @Aaron 遇到了完全相同的问题。之前必须定义与 var 相同的名称。例如,let StaticContainer : any 在这种情况下。不知道为什么会这样。
    • ES6 规范允许您导出单个项目。导出 object 不是静态可分析的,也不支持。
    猜你喜欢
    • 1970-01-01
    • 2019-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-09
    • 2017-03-02
    • 2019-03-30
    • 1970-01-01
    相关资源
    最近更新 更多