Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write a declaration file for a default export module

I have a npm module called RiveScript that usually (in Javascript) gets instantiated that way:

var RiveScript = require('rivescript'); var rivescript = new RiveScript(); 

I'm trying to write a declaration file for the module, but am stuck at the first step. Here's what I've written so far:

declare module "rivescript" {      interface RivescriptOptions {         utf8?: boolean;     }      class RiveScript {         constructor(options?: RivescriptOptions);     }      export default RiveScript; } 

Then I guess in Typescript I would be using the module this way (default import):

import RiveScript from 'rivescript'; let rivescript = new RiveScript(); 

However, tsc generates this, which is not valid as it references a default() function:

const rivescript_1 = require('rivescript'); let rivescript = new rivescript_1.default(); 

What am I doing wrong?

like image 567
julien_c Avatar asked Aug 23 '16 19:08

julien_c


People also ask

What is a declaration file?

Declaration files, if you're not familiar, are just files that describe the shape of an existing JavaScript codebase to TypeScript. By using declaration files (also called . d. ts files), you can avoid misusing libraries and get things like completions in your editor.

What is a module declaration?

3.2. 9 MODULE declarations. A module is an encapsulated collection of declarations. Once defined, a module can be reused as many times as necessary. Modules can also be so that each instance of a module can refer to different data values.

Why would you create a default export in a module?

Default Exports: Default exports are useful to export only a single object, function, variable. During the import, we can use any name to import.


1 Answers

You're really close. Instead of using export default, you should use export =.

custom-typings/rivescript.d.ts

declare module 'rivescript' {   class RiveScript {     constructor()   }   export = RiveScript } 

app.js

import RiveScript = require('rivescript'); let rivescript = new RiveScript(); 

For more info on how to write declaration files, you should have a look at the Typescript Handbook. Eg. they have a template for 'exporting modules as a class.

like image 133
Pelle Jacobs Avatar answered Sep 28 '22 19:09

Pelle Jacobs