Markdown in React with Typescript

2019-02-20 01:55发布

问题:

Is there a way to parse Markdown in React using Typescript?

I am trying to do things like:

import * as ReactMarkdown from 'react-markdown'
// OR
import ReactMarkdown = require('react-markdown')

But Typescript can't fint module 'react-markdown' as it's not defined:

Error: TS2307: Cannot find module 'react-markdown'.

How can I define the module and use it as a React component?

回答1:

I solved my problem by using commonmark package instead. They have typings and everything needed for my environment. Here is my implementation:

import { HtmlRenderer, Parser } from 'commonmark'

export class MyComponent extends React.Component<{}, {}> {
  private post: string

  constructor () {
    super()
    let parser = new Parser()
    let renderer = new HtmlRenderer()
    this.post = renderer.render(parser.parse("**works** like a charm!"))
  }

  render () {
    return (
      <div dangerouslySetInnerHTML={ {__html: this.post} } />
    )
  }
}

Also, do not forget to add the typings for commonmark:

$ typings install --global --save dt~commonmark

Thanks to the people who tried to help!