简体   繁体   English

TypeScript:如何从 JS 文件中导入所有导出函数,然后声明所有这些函数

[英]TypeScript: How to import all export functions from a JS file and then declare all those functions

I'm trying to create adts file for a js package so I can have typescript import functions from that package.我正在尝试为 js package 创建 adts 文件,以便我可以从该 package 导入 typescript 函数。 The package is using CommonJs style to define its exported functions. package 使用 CommonJs 样式定义其导出函数。 (Not an es6 file.) (不是 es6 文件。)

The package's main property from its package.json is directed to file: index.js .包的主要属性package.json指向文件: index.js The index.js file is displayed as: index.js文件显示为:

'use strict'

const Plugins = require('./Plugins')

module.exports = {
  plugins: Plugins
}

From the Plugis.js file:从 Plugis.js 文件中:

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

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

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

In pure JavaScript, this works, and I can use any of const Plugins exported functions.在纯 JavaScript 中,这是可行的,我可以使用任何const Plugins导出的函数。

I'm trying to create a typescript version index.d.ts with a similar make up:我正在尝试创建一个具有类似组成的 typescript 版本 index.d.ts:

'use strict'

import Plugins from './Plugins'

module.exports = {
  plugins: Plugins
}

However, I get errors when I import the js package and attempt to use the exported functions.但是,当我导入 js package 并尝试使用导出的函数时出现错误。 For example, can use plugins.function1() .例如,可以使用plugins.function1() I've been researching this topic and followed several examples, but I keep getting errors, such as if I declare the function I want to use, and examples use imports from es6 style files.我一直在研究这个主题并遵循了几个示例,但我不断收到错误,例如如果我声明了我想要使用的 function,并且示例使用了从 es6 样式文件中导入。 what is correct approach to import all file's functions?导入所有文件功能的正确方法是什么?

Solved my problem.解决了我的问题。 In addition to creating a index.d.ts I had to create a Plugins.d.ts file, then declare all the exported functions.除了创建 index.d.ts 之外,我还必须创建一个 Plugins.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};

For index.d.ts, my export and declare were off too, but I was able to correct it.对于 index.d.ts,我的导出和声明也关闭了,但我能够更正它。 index.d.ts: index.d.ts:

import * as Plugins from "./Plugins";

declare module "compatible-package-example" {
    export {Plugins}
}

Now when I import this package, I can use exported functions without issue.现在,当我导入这个 package 时,我可以毫无问题地使用导出的函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM