typescript - How to create a declaration for an npm module? -


i can't figure out how create declaration specific npm module. namely bbcode-to-react.

the main file indicated index.js , has little code:

'use strict';  var _parser = require('./parser');  var _parser2 = _interoprequiredefault(_parser);  var _tag = require('./tag');  var _tag2 = _interoprequiredefault(_tag);  function _interoprequiredefault(obj) { return obj && obj.__esmodule ? obj : { default: obj }; }  module.exports = new _parser2.default(); module.exports.parser = _parser2.default; module.exports.tag = _tag2.default; 

both './parser' , './tag' contain classes need.

i can't figure out typescript docs, how declare/export set-up in d.ts file. best can find related module.exports exporting single class or function need both parser , tag classes.

here typing bbcode-to-react:

declare module 'bbcode-to-react' {     import * react 'react';      function toreact(input: string): jsx.element;     function registertag(name: string, tag: typeof tag): void;      class tag {         name: string;         parent: jsx.element;         text: string;         params: { [index: string]: };         children: jsx.element[];          getcomponents(): jsx.element;         getcontent(raw?: boolean): string;         totext(contentashtml?: boolean): string;         tohtml(): string;         toreact(): jsx.element;     } } 

put code inside bbcode-to-react.d.ts file.

make sure have @types/react , @types/react-dom installed

an example using typing:

import * react 'react'; import * parser 'bbcode-to-react'; import { tag } 'bbcode-to-react'; import { rendertostring } 'react-dom/server';  const example1 = (props: any) => {     return (         <p>{parser.toreact('[b]strong[/b]')}</p>     ); }  console.log(rendertostring(<example1 />));  class youtubetag extends tag {     toreact() {         const attributes = {             src: this.getcontent(true),             width: this.params.width || 420,             height: this.params.height || 315,         };         return (             <iframe                 {...attributes}                 frameborder="0"                 allowfullscreen             />         );     } }  class boldtag extends tag {     toreact() {         return (             <b>{this.getcomponents()}</b>         );     } }  parser.registertag('youtube', youtubetag); parser.registertag('b', boldtag);  const example2 = (props: any) => {     return (         <p>{parser.toreact('[youtube width="400"]https://www.youtube.com/embed/ab6rjnedii0[/youtube]')}</p>     ); }  console.log(rendertostring(<example2 />)); 

Comments