2017-04-05 83 views
0

我无法弄清楚如何为特定的npm模块创建一个声明。即bbcode-to-react如何为npm模块创建声明?

主文件表示为index.js和只有一点点代码:

'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; 

两个“./parser”和“./tag”包含我需要的类。

我无法从打字稿文档中找出如何在d.ts文件中声明/导出这个设置。我能找到的与module.exports相关的最好的东西都是关于导出一个类或函数,但我需要解析器和标记类。

回答

1

这里是打字bbcode-to-react

declare module 'bbcode-to-react' { 
    import * as React from '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]: any }; 
     children: JSX.Element[]; 

     getComponents(): JSX.Element; 
     getContent(raw?: boolean): string; 
     toText(contentAsHTML?: boolean): string; 
     toHTML(): string; 
     toReact(): JSX.Element; 
    } 
} 

把这个代码bbcode-to-react.d.ts文件中。

请确保您有@types/react@types/react-dom使用此类型安装

一个例子:

import * as React from 'react'; 
import * as parser from 'bbcode-to-react'; 
import { Tag } from 'bbcode-to-react'; 
import { renderToString } from '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 />)); 
+0

感谢你为这个。我并不期待有人为我写信,但现在我可以看到它,我可以明白为什么它是以这种特殊方式设置的。 –

+0

我很高兴帮助你! :) – Diullei