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
380 views
in Technique[技术] by (71.8m points)

javascript - typescript declare third party modules

How could I declare a third party module which looks like this:

in third party module:

module.exports = function foo(){
  // do somthing
}

in my code:

import * as foo from 'foo-module'; // Can not find a declaration module for ...
foo();
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Check out the documentation on working with 3rd party modules.

How to write the declaration depends a lot on how the module was written and what it exports.

The example you've given is a CommonJS module (module.exports = ...) which is not really a valid ES6 module, because ES6 cannot export a function as the module (it can only export function members or a default function).

Update for TypeScript 2.7+

With the added esModuleInterop compiler option you no longer need to use the "namespace hack" shown below for CommonJS modules that have a non-ES6 compatible export.

First, make sure you've enabled esModuleInterop in your tsconfig.json (which is now included by default with tsc --init):

{
  "compilerOptions" {
    ...
    "esModuleInterop": true,
    ...
   }
}

Declare your foo-example in a .d.ts file like this:

declare module "foo-module" {
  function foo(): void; 
  export = foo;
}

Now you can import it as a namespace like you wanted:

import * as foo from "foo-module";
foo();

Or as a default import:

import foo from "foo-module";
foo();

Older workaround

You can declare your foo-example in a .d.ts file like this:

declare module "foo-module" {
  function foo(): void; 
  namespace foo { } // This is a hack to allow ES6 wildcard imports
  export = foo;
}

And import like you wanted:

import * as foo from "foo-module";
foo();

Or like this:

import foo = require("foo-module");
foo();

The documentation has a good resource on declaration files and some templates for various kinds of declaration files.


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

...