【问题标题】:TypeScript: How to import all export functions from a JS file and then declare all those functionsTypeScript:如何从 JS 文件中导入所有导出函数,然后声明所有这些函数
【发布时间】:2021-04-14 20:53:20
【问题描述】:

我正在尝试为 js 包创建一个 .d.ts 文件,以便我可以从该包中获得打字稿导入功能。该包使用 CommonJs 样式来定义其导出的函数。 (不是 es6 文件。)

来自package.json 的包的主要属性被定向到文件:index.jsindex.js 文件显示为:

'use strict'

const Plugins = require('./Plugins')

module.exports = {
  plugins: Plugins
}

来自 Plugis.js 文件:

module.exports.function1 = function1() {// function1 content};

module.exports.function2 = function2() {// function2 content};

module.exports.function3 = function3() {// function3 content};

在纯 JavaScript 中,这是可行的,我可以使用任何 const Plugins 导出的函数。

我正在尝试创建一个具有类似组成的打字稿版本 index.d.ts:

'use strict'

import Plugins from './Plugins'

module.exports = {
  plugins: Plugins
}

但是,当我导入 js 包并尝试使用导出的函数时出现错误。例如,可以使用plugins.function1()。我一直在研究这个主题并关注了几个示例,但我不断收到错误消息,例如如果我声明了我想要使用的函数,并且示例使用了从 es6 样式文件中导入。导入所有文件功能的正确方法是什么?

【问题讨论】:

    标签: javascript typescript import module export


    【解决方案1】:

    解决了我的问题。除了创建 index.d.ts 之外,我还必须创建一个 Plugins.d.ts 文件,然后声明所有导出的函数。

    插件.d.ts:

    declare export function1 = function1(): <Return value> {// function1 content};
    
    declare export function2 = function2(): <Return value> {// function2 content};
    
    declare export function3 = function3(): <Return value> {// function3 content};
    

    对于 index.d.ts,我的导出和声明也关闭了,但我能够更正它。 index.d.ts:

    import * as Plugins from "./Plugins";
    
    declare module "compatible-package-example" {
        export {Plugins}
    }
    

    现在当我导入这个包时,我可以毫无问题地使用导出的函数。

    【讨论】:

      猜你喜欢
      • 2018-09-11
      • 2021-09-28
      • 2018-10-27
      • 2020-09-20
      • 2017-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多