I try to do the declaration file of a library.
In the library.js
file there is:
if (typeof module !== 'undefined' /* && !!module.exports*/) {
module.exports = Library;
}
What should I put in my library.d.ts
file to be able to import and use this library in my code?
I expect to be able to do:
import { Library } from 'library';
const instance = new Library();
TypeScript supports export = to model the traditional CommonJS and AMD workflow. The export = syntax specifies a single object that is exported from the module. This can be a class, interface, namespace, function, or enum.
A module is a piece of code that can be called or used in another code. There is nothing new about modules in Typescript. The concept of the module was introduced by JavaScript with ECMAScript 2015 release. Typescript is just re-using this feature.
In TypeScript, files containing a top-level export or import are considered modules.
When we want to export a single class/variable/function from one module to another module, we use the module. exports way. When we want to export multiple variables/functions from one module to another, we use exports way.
You need to use the special export =
and import Library = require
syntax, as pointed out by @Nitzan:
export = and import = require()
A complete example:
node_modules/library/index.js
module.exports = function(arg) {
return 'Hello, ' + arg + '.';
}
library.d.ts
This filename technically does not matter, only the .d.ts
extension.
declare module "library" {
export = function(arg: string): string;
}
source.ts
import Library = require('library');
Library('world') == 'Hello, world.';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With