Correct way to setup Flow with draft-js

772 views Asked by At

I am trying to use Flow with draft-js.

package.json dependencies

...
"dependencies": {
  "draft-js": "^0.9.1",
  "immutable": "^3.8.1",
  "react": "^15.4.2",
  "react-dom": "^15.4.2"
},
"devDependencies": {
  "flow-bin": "^0.37.4"
}

I installed the type definitions with flow-typed by running flow-typed install.

Here's some slightly modified code I copied from draft-js docs which I am trying to validate with flow.

index.js

// @flow
import React from 'react';
import ReactDOM from 'react-dom';
import {Editor, EditorState} from 'draft-js';

class MyEditor extends React.Component {
  state: {
    editorState: EditorState
  }

  onChange: Function;

  constructor(props) {
    super(props);
    this.state = {editorState: EditorState.createEmpty()};
    this.onChange = (editorState) => this.setState({editorState});

    // gives type error, as expcted
    let a :string = 10;

    const editorState :EditorState = this.state.editorState;

    // should be a type error, editor.getCurrentContent() returns type ContentState
    const content :string = editorState.getCurrentContent(); 
  }

  render() {
    return (
        <Editor editorState={this.state.editorState} onChange={this.onChange} />
    );
  }
}

ReactDOM.render(
  <MyEditor />,
  document.getElementById('container')
);

.flowconfig

[ignore]
.*\/node_modules\/draft-js\/lib\/.*.js.flow.*

[include]

[libs]
.*\/node_modules\/draft-js\/lib\/.*.js.flow.*

[options]
esproposal.class_static_fields=enable
suppress_type=$FlowIssue
suppress_comment=\\(.\\|\n\\)*\\$FlowIssue

However, when I run flow command, I don't get any errors when I call draft-js API. What is the correct way to setup flow here for use with draft?

2

There are 2 answers

0
Andy VanWagoner On

If you have ignored files in your .flowconfig, then [libs] will also ignore them, so you'll need to remove .*\/node_modules\/draft-js\/lib\/.*.js.flow.* from [ignore].

In order to get flow & draft-js working together I also needed to set the suppress_comment to the same value used in draft-js:

[options]
suppress_comment=\\(.\\|\n\\)*\\$FlowFixMe\\($\\|[^(]\\|(\\(>=0\\.\\(2[0-8]\\|1[0-9]\\|[0-9]\\).[0-9]\\)? *\\).*\n
0
yuku-t On

The reason why Flow doesn't work with draft-js when import it as 'draft-js' is that:

  • draft-js' main file is lib/Draft.js. This means that import {Editor} from 'draft-js' equals to import {Editor} from 'draft-js/lib/Draft.js'.
  • From Flow version 0.19.0, it treats files that end with .flow (read this blog post) and draft-js 0.9.1 has lib/Draft.js.flow.
    • But it does not have @flow declaration.
  • (And you are ignoring draft-js in .flowconfig)

so you can solve this problem briefly by adding @flow to node_modules/draft-js/lib/Draft.js.flow. Or import Editor and EditorState from draft-js/lib/DraftEditor.react and draft-js/lib/EditorState respectively.