简体   繁体   中英

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. The package is using CommonJs style to define its exported functions. (Not an es6 file.)

The package's main property from its package.json is directed to file: index.js . The index.js file is displayed as:

'use strict'

const Plugins = require('./Plugins')

module.exports = {
  plugins: Plugins
}

From the Plugis.js file:

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.

I'm trying to create a typescript version index.d.ts with a similar make up:

'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. For example, can use 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. 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.

Plugins.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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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