Flow: Support node's require.main, require.resolve, etc.

Created on 3 Feb 2016  路  3Comments  路  Source: facebook/flow

Upgrading from 0.20.1 to 0.21.0 creates new failures for us:

lib/xyz.js:69
 69: if (require.main === module) {
                 ^^^^ property `main`. Property not found in
 69: if (require.main === module) {
         ^^^^^^^ statics of function type

All 3 comments

Hmm, sorry this is happening. We made this change intentionally, because it was unsound, but we should have called it out in the changelog. I'll update the changelog as well.

I have to admit some ignorance about the features Node has added to require. Right now we're in a position of supporting both node and browsers, which leaves us with a sort of lowest common denominator support. This is something we should work to improve. It comes up in other contexts as well. For example, node also hangs attributes off timers, which are non-standard in browsers.

My only recommendation for now is something like if ((require:any).main === module), i.e., opt-out of type checking locally. Alternatively, can you isolate this kind of code into a separate file which is not checked by Flow?

I'll update the changelog as well.

Thanks!

My only recommendation for now is something like if ((require:any).main === module), i.e., opt-out of type checking locally. Alternatively, can you isolate this kind of code into a separate file which is not checked by Flow?

Yeah, those were basically the workarounds I was considering. I understand your desire to support the lowest common denominator, but It'd be nice to be able to support require.main and require.resolve which are not too uncommon in node scripts. What if flow/lib/node.js supplied a type for Node's require attributes? That way we could write e.g. if ((require: node$require).main === module). It'd be even nicer of course if we could do something like declare var require: Function & node$require based on a flag in .flowconfig.

I'm not sure I'd know how to do the latter, but I'd be happy to throw up a PR to provide node$require if you think it's worthwhile.

Was this page helpful?
0 / 5 - 0 ratings