Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
381 views
in Technique[技术] by (71.8m points)

javascript - TypeScript: How to import all export functions from a JS file and then declare all those functions

I'm trying to create a .d.ts 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?

question from:https://stackoverflow.com/questions/65641018/typescript-how-to-import-all-export-functions-from-a-js-file-and-then-declare-a

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...